一旦我作为itemName输入,为什么我的程序会继续?

时间:2014-09-05 21:40:40

标签: java

我无法弄清楚为什么我的程序在输入字符串"结束"之后不会继续经过while循环。作为其中一个项目。我尝试在while循环之后放置println语句,并且在输入" end"之后它们没有打印。我还尝试在while循环结束时放置一个print语句,并且在键入" end"后它没有打印,因此在输入" end&之后它不会运行while循环#34;,但它也不会在它之后运行任何东西。有任何想法吗?这是代码:

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);


           }

    }

1 个答案:

答案 0 :(得分:3)

如果你写完&#34;结束&#34;它会停止后跟一个int,另一个int和一个double。

这是因为您首先检查&#34;结束&#34;,然后要求输入4个。

在每个循环开始时评估while(条件)。

所以你的程序是这样的:

  1. 检查itemName是否等于&#34;结束&#34;
  2. 询问itemName
  3. 询问categoryNumb
  4. 询问数量
  5. 询问费用
  6. 做你的东西
  7. 回到1
  8. 如果您想在用户输入&#34;结束&#34;将其更改为:

    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