Java字符串索引越界,CharAt问题。

huangapple go评论67阅读模式
英文:

Java string index out of bound , CharAt problem

问题

代码抛出一个错误:"String index out of bound : 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("猜一个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("你猜的数字是:" + sa);
        System.out.println("正确的数字是:" + s);

        if (str2.charAt(0) == str1.charAt(0) && str2.charAt(1) == str1.charAt(1)) {
            System.out.println("恭喜你,你以正确的顺序猜对了,赢得了1000美元!");
        } else if (str1.charAt(0) == str2.charAt(1) && str1.charAt(1) == str2.charAt(0)) {
            System.out.println("恭喜你,你猜对了数字,但顺序错误,赢得了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("恭喜你,你猜对了其中一个数字!");
        } else {
            System.out.println("抱歉,你猜错了,请再试一次");
        }
    }
}

任务说明是:“一个彩票程序生成一个01-99之间的双位数。如果用户按正确顺序猜出数字,则赢得1000美元。如果用户按错误顺序猜出正确的数字,例如16代替61,则赢得500美元。如果用户猜对其中一个数字,赢得100美元。”

当用户输入和/或randomNum大于等于10时,代码运行正常。然而,当它小于10时,会出现错误,因为值被解释为1个字符而不是2个字符,例如:09被解释为9,所以charAt(1)不存在。

如何修复这个问题?是否有办法使0被视为charAt(0),这样charAt(1)就可以计算0后面的数字,还是需要改变其他内容?

谢谢!

英文:

my code is throwing an error "String index out of bound : 1" , here is the code :

     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");
}
}
}

The assignment instructions are : "A lottery program generates a double digit number between 01-99. If the user guesses the number right in the right order, they win 1000$. If the user guesses the right number in the wrong order, example 16 instead of 61, they win 500$. If the user guesses one of the numbers right, they win 100$."

The code is working fine when user input and/or randomNum are 10 and above. However ,when it is below 10 , the error occurs because the value is read as 1 char instead of 2, example : 09 is read as 9 , so charAt(1) does not exist.

How can I fix this? Is there a way to make 0 count as charAt(0) so that charAt(1) counts the digits after the 0, or do I need to change something else?

Thanks!

答案1

得分: 2

正如我在评论中提到的:您有String sa = String.format("%02d",value);,但在主代码中使用str1。改用sa,即使数字小于10,它也将有2个字符。

另一个选项是不使用字符串。这里是一个仅使用数学的版本。

public static void randomNumber() {
    System.out.println("猜一个01-99之间的数字");
    Scanner scanner = new Scanner(System.in);
    Random random = new Random();
            
    int value = Integer.valueOf(scanner.nextLine());
    // TODO: 添加检查,要求 1 <= value <= 99
    int randomNum = random.nextInt(98) + 1;
    
    System.out.printf("你猜的是:%02d%n", value);
    System.out.printf("正确的数字是:%02d%n", randomNum);
    
    // 检查是否完全匹配
    if (value == randomNum) {
        System.out.println("恭喜你,你以正确的顺序猜对了数字,赢得了1000美元!");
        return;
    }
    
    // 获取随机数字的个位和十位数字(对于个位数也适用)
    int randOnes = randomNum % 10;
    int randTens = randomNum / 10;

    // 检查逆序匹配
    if (value == (randOnes * 10 + randTens)) {
        System.out.println("恭喜你,你猜对了数字,但顺序错误,赢得了500美元!");
        return;
    }
    
    // 获取用户的个位和十位数字
    int userOnes = value % 10;
    int userTens = value / 10;

    // 检查单个数字匹配
    if (userOnes == randOnes || userOnes == randTens || userTens == randOnes || userTens == randTens) {
        System.out.println("恭喜你,你猜对了其中一个数字!");
        return;
    }
    System.out.println("抱歉,你猜错了,请再试一次");
}
英文:

As I mentioned in the comments: You have String sa = String.format(&quot;%02d&quot;, value); but you use str1 in the main code. Use sa instead which will have 2 chars even if the number is less than 10.

Another option is to not use strings. Here is a math only version.

public static void randomNumber () {
{
System.out.println(&quot;Guess a number between 01-99&quot;);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int value = Integer.valueOf(scanner.nextLine());
// TODO: add a check 1 &lt;= value &lt;= 99
int randomNum = random.nextInt(98) + 1;
System.out.printf(&quot;You guessed :%02d%n&quot;, value);
System.out.printf(&quot;The correct number is : %02d%n&quot;, randomNum);
// Check for exact match
if (value == randomNum) {
System.out.println(&quot;Congratulations, you guessed the right number in the right order and won 1000$!&quot;);
return;
}
// Get the digits of the random number (works for single digit numbers, too)
int randOnes = randomNum % 10;
int randTens = randomNum / 10;
// Check for reverse match
if (value == (randOnes * 10 + randTens)) {
System.out.println(&quot;Congratulations, you guessed the right number but in the wrong order and won 500$ !&quot;);
return;
}
// Get user&#39;s digits
int userOnes = value % 10;
int userTens = value / 10;
// Check for single digit match
if (userOnes == randOnes || userOnes == randTens || userTens == randOnes || userTens == randTens) {
System.out.println(&quot;Congratulations, you guessed one of the numbers right!&quot;);
return;
}
System.out.println(&quot;Sorry you guessed wrong, try again&quot;);
}

huangapple
  • 本文由 发表于 2020年10月13日 20:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64335017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定