我的代碼應該要求輸入一個名字,請求一個介於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感謝您的反饋 –