gpt4 book ai didi

java - 如何使用 'for' 循环来检查输入中的某些数字?

转载 作者:行者123 更新时间:2023-11-30 07:08:19 25 4
gpt4 key购买 nike

我是java新手,对使用循环也很陌生,到目前为止,我一直在为我的类(class)解决一个问题,制作一个程序来检查用户是否输入随机生成的正确数字的变体,但它说一旦循环开始,就无法找到lotteryNumberString。有关如何修复它的任何提示吗?

    import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

for(int i=0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);

String lotteryNumberString = Integer.toString(lotteryNumberDigit);

}



String firstNumber = lotteryNumberString.substring(0,0);
String secondNumber = lotteryNumberString.substring(1,1);
String thirdNumber = lotteryNumberString.substring(2,2);

String firstTwoWinner = firstNumber + secondNumber;
String lastTwoWinner = secondNumber + thirdNumber;
String allNumbersWinner = firstNumber + secondNumber + thirdNumber;

System.out.println("Please enter your three numbers (e.g. 123): ");

String userInput = input.next();

if(userInput.substring(0,2).equals(firstTwoWinner))

{
System.out.println("Winner: " + allNumbersWinner );

System.out.println("Congratulations, the front pair matched.");
}

else if (userInput.substring(1,3).equals(lastTwoWinner))
{
System.out.println("Winner: " + allNumbersWinner );

System.out.println("Congratulations, the end pair matched.");
}

else if (userInput.equals(allNumbersWinner))
{
System.out.println("Winner: " + allNumbersWinner );

System.out.println("Congratulations, both pairs matched.");
}

else
{
System.out.println("Winner: " + allNumbersWinner );

System.out.println("Sorry, no matches. You only had one chance out of 100 to win anyway.");
}



}
}

最佳答案

看看这篇文章:http://www.java-made-easy.com/variable-scope.html 。您面临的问题与lotteryNumberString 变量的范围(生命周期)有关。如果您在循环内部声明,则它不存在于循环外部。要解决此问题,请在 for 循环之前声明lotteryNumberString

关于java - 如何使用 'for' 循环来检查输入中的某些数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683688/

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