2014-09-05 26 views
0

我找不到爲什麼我的程序不會繼續通過while循環,一旦我輸入字符串「end」作爲其中一項。我試着在while循環之後放置println語句,並在輸入「end」後不打印。我也嘗試在while循環的末尾放置一個print語句,並且一旦我鍵入「end」,它就不會打印,因此在鍵入「end」之後它不會運行while循環,但它也不會運行任何操作之後。有任何想法嗎?這裏的代碼:作爲itemName輸入後,爲什麼我的程序不會繼續運行?

package a1; 

import java.util.Scanner; 

public class A1Adept { 
    public static void main(String[] args) { 
      Scanner s = new Scanner(System.in); 

      process(s); 
    } 

    public static void process(Scanner s) { 

      int[] numbers = new int[10]; 
      double[] cost = new double[10]; 
      String itemName = ""; 
      int categoryNumb; 
      int quantities; 
      double costs; 

      System.out.println("Please enter the names of the items, their category, their quantity, and their cost."); 

      while(!itemName.equals("end")){    

       itemName = s.next(); 
       categoryNumb = s.nextInt(); 
       quantities = s.nextInt(); 
       costs = s.nextDouble(); 

       numbers[categoryNumb] += quantities; 
       cost[categoryNumb] += (costs*quantities); 

       } 
      System.out.println("win"); 
      int qMax = 0; 
      int qMin = 0; 
      int cLarge = 0; 
      int cLeast = 0; 
      int max = 0; 
      int min = 100; 
      double large = 0; 
      double least = 100; 

      for (int i = 0; i < 10; i++){ 
       if (numbers[i] >= max) 
       { 
        max = numbers[i]; 
        qMax = i; 
       } 
       if (numbers[i] <= min){ 
        min = numbers[i]; 
        qMin = i; 
       } 
       if (cost[i] >= large){ 
        large = cost[i]; 
        cLarge = i;     
       } 
       if (cost[i] <= least){ 
        least = cost[i]; 
        cLeast = i; 
       } 
      } 

      System.out.println("Category with the most items:"+qMax); 
      System.out.println("Category with the least items:"+qMin); 
      System.out.println("Category with the largest cost:"+cLarge); 
      System.out.println("Category with the least cost:"+cLeast); 


      } 

    } 

回答

3

它會停止,如果你寫「結束」後面跟着一個int,另一個int和一個雙。

這是因爲您首先檢查「結束」,然後詢問4個輸入。

while(條件)在每個循環的開始處評估。

所以,你的程序是這樣的:

  1. 檢查ITEMNAME等於 「結束」
  2. 向ITEMNAME
  3. 向categoryNumb
  4. 賣出量
  5. 向成本
  6. 做你的東西
  7. 返回1

如果你想盡快當用戶鍵入退出「結束」將其更改爲:

 
while (true) { // Creates an "endless" loop, will we exit from it later 
    itemName = s.next(); 
    if (itemName.equals("end")) break; // If the user typed "end" exit the loop 
    // Go on with the rest of the loop 
+0

嗨,如果這個答案解決您的問題,請接受它。 – 2014-09-08 12:11:54

相關問題