我的代码应该要求输入一个名字,请求一个介于1到10之间的数字,从1打印数字到用户输入的数字,除了第三个数字应该是 是用户输入的名字编程,打印偶数,不断向用户询问数字,直到用户输入标记,然后打印输入的总数。 (我知道,这很多。)我的代码运行良好,我遇到的唯一问题是最后一部分。即使用户输入哨兵(在本例中为-1),该程序仍要求输入其他条目。如何纠正我的哨兵值?
当我声明变量或有人可以解释如何解决我的问题时,我做错了吗?这是我的代码。
import java.util.Scanner;
/**
*
* @author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
while (inputNumber != SENTINEL)
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println("The total is " + total);
}
}
投票,如果它帮助感谢 –
询问票往往会带来相反的效果。 OP也没有足够的声望进行投票。 – Pshemo
@Pshemo感谢您的反馈 –