【发布时间】:2020-02-28 05:50:15
【问题描述】:
我真的,真的很困惑,很困惑。我已经上网搜索了好几次,但找不到任何可以帮助我解决这个精确的作业问题的东西。
涉及:Java、while 循环、随机生成数字和扫描仪控制台输入。
我们必须在 main 方法中完成代码,以便它从控制台获取两个单独的输入并生成一些“滚动”,然后当它们是一对数字时显示结果,一个偶数,一个奇数。
编辑:有人指出我的措辞令人困惑。 Joseph Larson 措辞更好:
“你是要求随机数的上界,然后运行多少次,对吗?”是的,就是这样。
我有两个主要问题。如果这些都解决了,我很确定我能解决剩下的问题。
1) 我知道我应该做一些事情来完成 while 循环,但我尝试过的都没有得到所需的结果。
2) 我认为我错误地声明了 randUpBound 和 oddeven 项,但我无法弄清楚如果我有我可能做错了什么。
最奇怪的部分是我的大多数尝试都创建了一个空白的无限循环——什么都没有显示,但 IntelliJ 发誓程序正在运行,并且在我让它停止之前它不会停止。甚至引号中的字符串都不会出现。
下面的预期显示和代码。我已经把//添加到我的代码所在的行,并留在老师的说明中。
感谢您提供的任何帮助!
预期展示
输入随机上限? 12
输入要计数的奇偶对数? 2
掷出的数字:11、2
- 找到奇数+偶数对! 11,2
掷出的数字:1、8
- 找到奇数+偶数对! 1、8
掷出的数字:1、1
总卷数:6
代码
导入 java.util.*; //添加
公共类 OddEvenPairs { public static void main(String[] args) {
//.....[add in missing code here - make declarations and add console input for the random number upper bound,
// and the number of odd-even pairs to be counted]
//read two consecutive numbers - fencepost
Scanner console = new Scanner(System.in); //added
Random rand = new Random(); //added
int randUpBound = console.nextInt(); //added
int oddeven = console.nextInt(); // added
System.out.println("Enter random upper bound? " + randUpBound); //added
System.out.println("Enter number of odd even pairs to count? " + oddeven); //added
int roll1 = rand.nextInt(randUpBound);
int roll2 = rand.nextInt(randUpBound);
System.out.println("Numbers " + roll1 + ", " + roll2);
int rollcount = 2;
int oddEvenNum = roll1 + roll2;
//process the numbers
while (oddeven < oddEvenNum) {
oddeven = oddEvenPair(roll1, roll2, oddeven);
roll1 = rand.nextInt(randUpBound);
roll2 = rand.nextInt(randUpBound);
System.out.println("Numbers " + roll1 + ", " + roll2);
rollcount += 2;
//.....[complete missing code here]
}
}
//method to figure out odd-even pair
public static int oddEvenPair(int roll1, int roll2, int oddeven) {
//boolean oddEvenFound = false;
if (roll1 % 2 == 1) {
if (roll2 % 2 == 0) {
//oddEvenFound = true;
oddeven++;
System.out.println("Odd even " + oddeven);
System.out.println("Odd+even pair found!" + roll1 + "," + roll2);
}
}
return oddeven;
}
}
【问题讨论】:
-
好的,你的问题的措辞令人困惑,所以我会尝试重新措辞。你是求随机数的上界,然后运行几次,对吗?因此,如果我输入 35 和 17,那么 17 次您将生成从 0 到 35 的两个数字,然后输出它是奇数、偶数还是各一个。是吗?
-
是的,没错。很抱歉没有说得更清楚。
标签: java random while-loop console-input