在Java

时间:2017-04-20 16:50:55

标签: java loops while-loop

我正在为我的作业制作一个程序。这不是整个计划,但它只是其中的一部分。

我希望用户输入一些整数值以存储在“items”数组中。当用户输入“停止”时,循环应该关闭,这就是问题..当我写停止时,程序停止并给我一些错误。

 public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
     int i=0, lines=1;
     int[] items = new int[100];
     int total = 0;
     System.out.println("Enter the items with its price");

     while(true){
          i=i+1;
          if ("stop".equals(scan.nextLine()))
              break;
          else
              items[i] = scan.nextInt();
     } 

 }

3 个答案:

答案 0 :(得分:1)

您的代码中存在某些错误。如果您只是添加错误,情况会更好。

试试这段代码。

public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
     int i = 0, lines = 1;
     int[] items = new int[100];
     int total = 0;
     System.out.println("Enter the items with its price");

     while(true){
          String InputTxt = scan.nextLine();
          if (InputTxt.equals("stop"))
              break;
          else{           
              try{
                 items[i] = Integer.parseInt(InputTxt);
                 i++;
              }catch(Exception e){
                 System.out.println("Please enter a number");
              }
          }

     } 

 }

答案 1 :(得分:1)

除了其他答案之外,我还建议您更改

的循环
while(true)

//first you need to remove the local variable i 
for(int i = 0; i < items.length; ++i)

当用户输入超过100个整数值时,使用此方法可以帮助您避免 IndexOutOfBoundsException

答案 2 :(得分:-1)

你的问题是这一行:items[i] = scan.nextInt();因为你试图获得整数,而输入是字符串stop

修改 一种可能的解决方案是,您将数据作为字符串获取并检查它是否为stop,如果没有,则尝试将其解析为整数,如下所示:

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true)
    {
    i=i+1;
     String str = scan.nextLine()
     if ("stop".equals(str))
         break;
     else
         {
         items[i] =  Integer.parseInt(str)
         }
    }
}