【发布时间】:2020-10-13 12:11:35
【问题描述】:
我的代码抛出错误“字符串索引超出范围:1”,这是代码:
package inlamningsuppgift2;
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class inlamningsuppgift2del2 {
public static void main(String[] args) {
System.out.println("Guess a number between 01-99");
randomNumber();
}
public static void randomNumber () {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int value = Integer.valueOf(scanner.nextLine());
String str1 = Integer.toString(value);
String sa = String.format("%02d", value);
int randomNum = 10 * random.nextInt(9);
int randomNum2 = 1 * random.nextInt(9) +1;
int wholeNum = randomNum + randomNum2;
String str2 = Integer.toString(randomNum + randomNum2);
String s = String.format("%02d", randomNum + randomNum2);
System.out.println("You guessed :" + sa);
System.out.println("The correct number is : " + s);
if (str2.charAt(0) == str1.charAt(0) && str2.charAt(1) == str1.charAt(1)) {
System.out.println("Congratulations, you guessed the right number in the right order and won 1000$!");
}
else if (str1.charAt(0) == str2.charAt(1) && str1.charAt(1) == str2.charAt(0) ) {
System.out.println("Congratulations, you guessed the right number but in the wrong order and won 500$ !");
}
else if (str2.charAt(0) == str1.charAt(0) && str2.charAt(1) != str1.charAt(1)
|| str2.charAt(0) != str1.charAt(0) && str2.charAt(1) == str1.charAt(1)
|| str1.charAt(1) == str2.charAt(0) && str1.charAt(0) != str2.charAt(1)
|| str1.charAt(0) == str2.charAt(1) && str1.charAt(1) != str2.charAt(0)) {
System.out.println("Congratulations, you guessed one of the numbers right!");
}
else {
System.out.println("Sorry you guessed wrong, try again");
}
}
}
分配指令是:“一个彩票程序生成一个介于01-99之间的两位数。如果用户以正确的顺序猜对数字,他们将赢得1000美元。如果用户以错误的顺序猜对数字,例如 16 而不是 61,他们赢了 500 美元。如果用户猜对了其中一个数字,他们就赢了 100 美元。”
当用户输入和/或 randomNum 为 10 及以上时,代码工作正常。但是,当它低于 10 时,会发生错误,因为该值被读取为 1 char 而不是 2,例如:09 被读取为 9 ,因此 charAt(1) 不存在。
我该如何解决这个问题?有没有办法让 0 计为 charAt(0) 以便 charAt(1) 计算 0 之后的数字,还是我需要更改其他内容?
谢谢!
【问题讨论】:
-
您应该直接比较数字,或者使用简单的
==用于原始int或equals方法用于Integer。将您的数字转换为字符串,然后将这些字符串转换为字符并比较这些字符是不必要的复杂,并且会引入您当前遇到的问题。 -
你有
String sa = String.format("%02d", value);,但你在主代码中使用str1。使用sa代替,即使数字小于 10 也会有 2 个字符。 -
@OHGODSPIDERS 感谢您的建议,我以后会考虑的,