Java:变量已在方法中定义 [英] Java: Variable is already defined in method

查看:45
本文介绍了Java:变量已在方法中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个程序,它在 1000-9999 之间生成一个没有重复数字的随机数.规则是我必须将随机数标记为字符串,然后使用 while 循环来确定是否有任何数字重复.

I am trying to make a program which makes a random number between 1000-9999 with no repeating numbers. The rules are I have to label the random number as a String, and then use a while loop to figure out if any of the numbers repeat.

//generating random number
double answer1 = (Math.random() * 9000)+1000;

//converting answer
int answer2 = (int)answer1;
String answer = answer2 + " ";

//Labeling arrays
answer.toCharArray();

//**NEW** checking random number
while (answer.charAt(0) == answer.charAt(0)
       || answer.charAt(0) == answer.charAt(1)
       || answer.charAt(0) == answer.charAt(2)
       || answer.charAt(0) == answer.charAt(3)
       || answer.charAt(1) == answer.charAt(1)
       || answer.charAt(1) == answer.charAt(2)
       || answer.charAt(1) == answer.charAt(3)
       || answer.charAt(2) == answer.charAt(2)
       || answer.charAt(2) == answer.charAt(3)
       || answer.charAt(3) == answer.charAt(3)); //you have my apologies
{
    ////generating random number
    double answer1 = (Math.random() * 9000)+1000;

    //converting answer
    int answer2 = (int)answer1;
    String answer = answer2 + "
}

我知道 while 参数非常长,但有必要确保没有重复的数字.我假设我可以重新生成一个新的随机数并在 while 循环中再次测试它,但是我收到错误,变量 answer1、answer 和 answer2 已经在我的主要方法中定义.有没有人知道我可以做些什么来生成新的随机数,直到没有重复的数字?

I know the while parameters are extremely long, but it was necessary to make sure none of the numbers repeated. I assumed that I could regenerate a new random number and test it again in the while loop, but I get the error that variables answer1, answer, and answer2 are already defined in my main method. Does anyone have a tip as to what I can do to generate a new random number until none of the numbers repeat?

推荐答案

您已经在 line 2 中定义了变量 answer2,并且在 while 循环中试图重新定义变量 answer2,即:

You've already define your variable answer2 in line 2, and in your while loop you are trying to redefine the variable answer2, i.e:

int answer2 = (int)answer1;

你可以这样做:

answer2 = (int)answer1;

这篇关于Java:变量已在方法中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆