2014-09-05 58 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

相关问题