我对Java很陌生,需要帮助。基本上,我有一个要求用户输入数字的程序。输入数字时,它将取该数字之前的所有奇数之和,并将它们加起来。我正在尝试(但失败)的是,进行另一个循环,借此,当系统提示用户要求输入一个数字以对奇数进行求和时,我要这样做,以便仅在奇数时才继续输入,否则它将反复询问用户,直到他们输入奇数为止。我知道使用while
循环可以解决此问题,但是我不确定如何使它工作。
这是我的代码:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
谢谢!
答案 0 :(得分:2)
continue;
,因为一条语句“向上和向下”扫描可以继续的第一个结构。当前只有for
,while
和do/while
语句可以继续执行操作,因此它找到while (number % 2 != 0)
并将继续执行。
继续进行while循环意味着:直接跳回条件number %2 != 0
,对其求值,如果为true,则再次进入循环;如果为false,则跳至}
。
因此,您的代码检查数字是否为奇数。如果是,它将继续..。因此,它将..检查数字是否为奇数。如果是,它将检查数字是否为奇数。如果是,它将永远检查数字是否为奇数。...
大概您的目的是再次询问用户,但是随后您必须将循环包装在更多代码周围:以print
开始,因为肯定sc.nextInt()
必须在内部循环。那确实意味着您没有要检查的number
值,但这就是do / while循环的目的:确保您至少循环一次(以便您可以将循环中计算出的任何内容用作循环的一部分)条件)。
答案 1 :(得分:0)
如果数字不是奇数,还应该在while
循环内使用扫描仪。
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
答案 2 :(得分:0)
您的困惑似乎来自误解,即continue
意味着回到while
循环,而break
是使您跳出循环的原因。这对您有用吗?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
答案 3 :(得分:0)
我希望此输出是您要寻找的,以前的代码不起作用的原因是number = sc.nextInt();
是可以提示用户输入内容的原因,因此必须循环输入,此外,您可以根据用户在if语句中输入的内容给出具体的提示,希望对您有所帮助!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
输出:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4