gpt4 book ai didi

java - 来自给定列表的用户输入,混合了 String 和 Int

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:07 25 4
gpt4 key购买 nike

我正在尝试 Java,但根本没有接受过正式培训。我从某个地方的类(class)中收到了一份作业,并想尝试一下。到目前为止,一切进展顺利,除了我需要让用户进行输入(从给定列表中进行选择)。我在处理字符串值时没有任何问题,但他们也可以选择从 0-39 之间选择一个数字,我希望将其存储为 int。

如有任何帮助,我们将不胜感激。

import java.util.Scanner;

public class RouletteGame {

static Player p1;
public static void main(String[] args){

Scanner scan = new Scanner(System.in);
int num = (int)(Math.random()*37);
int winnings = 0;
int x = 0;
int counter = 1;
int p = 1;
String name;
String choice;
int iAmount = 100;
int betNum;

System.out.println("Welcome to Cache Creek style Rouylette..bet an amount and type");
System.out.println(" if you select the correct colour, you win double your bet");
System.out.println(" if you select the correct odd/even, you win double your bet");
System.out.println(" if you select the correct number, you win 40 times your bet");
System.out.println(" otherwise you lose your bet");
System.out.println("If you lose all your money, the game is over");
System.out.println();
System.out.print("How much do you want to bet? $");
int bet=scan.nextInt();

while (x==0){
Scanner scann = new Scanner(System.in);
System.out.println("What is your bet? (odd/even/red/black/exact number)");
choice=scann.nextLine();
}

if (choice.equals("odd")){
System.out.println("You have selected odd.");
x=1;
}
else if (choice.equals("even")){
System.out.println("You have selected even.");
x=1;
}
else if (choice.equals("red")){
System.out.println("You have selected red.");
x=1;
}
else if (choice.equals("black")){
System.out.println("You have selected black.");
x=1;
}
else if (choice.equals(int)){
betNum = Integer.parseInt(choice);
System.out.println("You have selected " +betNum);
x=1;
}
else{
System.out.println("Invalid value: Must be odd, even, red, black or a number between 0 and 39");
x=0;
}
}
}
}

最佳答案

问题是您不知道给定的答案是字符串还是整数。

此行无法编译:

else if (choice.equals(int)) {

相反,创建一个新方法 isInteger(String s),例如 this one并在上面一行的位置调用它,如下所示:

else if (isInteger(choice)) {
betNum = Integer.parseInt(choice);
if (betNum >= 0 && betNum <=39) {
System.out.println("You have selected " +betNum);
x = 1; //by the way, you can set x to be a boolean variable
} else { //betNum not a valid Roulete number
System.out.println("Invalid value: Must be odd, even, red, black or a number between 0 and 39");
x=0;
}
}

关于java - 来自给定列表的用户输入,混合了 String 和 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26758678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com