gpt4 book ai didi

java - 创建 2 个随机输入数字,然后询问解决方案以及用户是否想要添加另外 2 个数字

转载 作者:行者123 更新时间:2023-11-30 03:01:25 24 4
gpt4 key购买 nike

import java.util.Scanner;
public class mathstrainer {

public static void main(String[] args) {
Scanner answerinput=new Scanner(System.in);
System.out.println("Welcome to Maths Trainer!");
boolean choice=true;
int max=15;
int min=1;
while(choice=true){
int number1=(int)(Math.random()*max+min);
int number2=(int)(Math.random()*max+min);
System.out.println("what is "+number1+"+"+number2+"? >");
int answer=answerinput.nextInt();
int solution=number1+number2;
if(answer==solution){
System.out.println("Correct! Well done!");
System.out.println("Would you like another question? (Y/N)");
String choiceword=answerinput.nextLine();
choiceword=choiceword.toUpperCase();
char choiceletter=choiceword.charAt(0);
if(choiceletter=='Y'){
choice=true;
}
else{
choice=false;
}

}
else{
System.out.println("Incorrect! The right answer is "+solution);
System.out.println("Would you like another question? (Y/N)");
String choiceword=answerinput.nextLine();
choiceword=choiceword.toUpperCase();
char choiceletter=choiceword.charAt(0);
if(choiceletter=='Y'){
choice=true;
}
else{
choice=false;
}
}
}}}

它伴随着问题:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at mathstrainer.main(mathstrainer.java:36)

我哪里出了问题,该如何解决?

我正在尝试使用 boolean 变量创建一个循环来充当问题创建者和重复器,但可以通过将 boolean 值设置为 false 来停止循环。

此外,这个问题到底意味着什么?我似乎经常遇到同样的问题。

最佳答案

当您调用 answerinput.nextInt() 时,扫描器会读取整数并在同一行中继续,之后,answerinput.nextLine() 将读取输入,直到找到一个换行符,在您的情况下返回一个空字符串。可能的解决方案:

  • nextInt() 之后添加 nextLine() 以读取换行符。
  • nextLine() 替换为 next()Scanner.next() 将查找输入中的下一个标记。

关于java - 创建 2 个随机输入数字,然后询问解决方案以及用户是否想要添加另外 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35834214/

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