2014-02-22 59 views
1

編寫使用while循環的程序。在循環的每次迭代中,提示用戶輸入一個數字 - 正數,負數或零。保持用戶輸入的總數,並保持用戶輸入的數量。只要用戶輸入「q」退出,程序應停止。用戶完成後,打印總計和用戶輸入的條目數量。用字符串終止循環。 (Java)

我可以讓這個程序工作,當我輸入一個數字如0,終止循環。但我不知道如何獲得它,以便一個字符串阻止它。

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    int count = 0; 
    int sum = 0; 
    int num; 
    System.out.println("Enter an integer, enter q to quit."); 
    num = in.nextInt(); 
    while (num != 0) { 
     if (num > 0){ 
     sum += num; 
     } 
     if (num < 0){ 
     sum += num; 
     } 
     count++; 
     System.out.println("Enter an integer, enter q to quit."); 
     num = in.nextInt(); 
    } 
    System.out.println("You entered " + count + " terms, and the sum is " + sum + "."); 

} 
+0

你的意思是像試圖讀入一個字符串並檢查它是否等於'「q」'? (加上檢查用戶是否輸入了號碼等等) –

回答

1

你的策略是將輸入作爲一個字符串,檢查它是否是「q」,如果不轉換爲數字和循環。

(因爲這是你的項目,我只提供了策略,而不是代碼)

這是粗略的策略:

String line; 
line = [use your input method to get a line] 
while (!line.trim().equalsIgnoreCase("q")) { 
    int value = Integer.parseInt(line); 
    [do your work] 
    line = [use your input method to get a line] 
} 
+0

如果您不舒服或不知道如何檢查Java API,我們可以推薦一些方法供您使用 – ForgetfulFellow

0

java的期望一個整數,但我們應該給予同樣的異常。解決這個問題的一種方法是輸入一個字符串,這樣如果用戶第一次按下Q就不會進入循環,如果不是Q.我們假設用戶是專家,並且只有當你輸入數字和Q時完成。內,而我們將字符串與num.parseInt(字符串)對數

Integer num; 
String input; 
while(!input.equal(q)){ 
num=num.parseInt(input) 
    if(num<0) 
    sum+=1; 
    else 
    sumA+=1; 
} 
0
public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    int count = 0; 
    int sum = 0; 
    String num; 
    System.out.println("Enter an integer, enter q to quit."); 
    num = in.next(); 
    while (!num.equals("q")) { 
      sum += Integer.parseInt(num); 
     count++; 
     System.out.println("Enter an integer, enter q to quit."); 
     num = in.next(); 
    } 
    System.out.println("You entered " + count + " terms, and the sum is " + sum + "."); 

    } 

減少了你的代碼升技是簡單易懂,讓你正是你想要的。

也可以添加一個if語句來檢查他們是否輸入了另一個隨機值(所以如果用戶沒有聽,程序不會崩潰)。例如:

if(isLetter(num.charAt(0)) 
    System.out.println("Not an int, try again"); 

會放在while循環之後,因此它已經檢查過它是否是q。