简体   繁体   English

Java Integer.parseInt()中断程序

[英]Java Integer.parseInt() breaks program

I have a question to do in my Java class, and it asks me to write a program that takes in n numbers from the user and outputs the average of them. 我在Java类中有一个问题要解决,它要求我编写一个程序,该程序接收用户的n个数字并输出它们的平均值。 I know I could do it a much simpler way, just by asking the user to enter the amount of values (s)he needs to enter at the beginning, but I want to create the program so the user doesn't necessarily have to know the number of values at the beginning. 我知道我可以用一种更简单的方法来完成此工作,只需要求用户输入开始时需要输入的值的数量即可,但是我想创建该程序,因此用户不必一定要知道开头的值数。 So for this, I create an array of 100 length (which hopefully covers the amount the user needs to enter) inside a for loop (rendering that 100 length array null after the loop, so the program doesn't become too memory heavy) and running a counter trough each iteration. 因此,为此,我在for循环内创建了一个100长度的数组(希望可以覆盖用户需要输入的数量)(在循环后将100长度的数组呈现为空,这样程序就不会变得太占用内存)每次迭代都运行一个计数器槽。 Once the user enters stop, the loop ends, and the values entered into the 100 length array gets transferred to an array the size of the count. 一旦用户进入停止位置,循环就结束了,并且输入到100长度数组中的值将被转移到一个计数大小的数组中。 Here is the code: 这是代码:

import java.util.*;
import java.lang.*;

public class main
{
   public static void main(String args[])
   {
      Scanner input = new Scanner(System.in);
      //Question 1
      System.out.println("Enter your numbers. (Enter 'Stop' when you're done)");
      int temp = 0;
      String uInput = "";
      char stopper;
      int count = 0;
      double total = 0;
      int a = 0;
      boolean inStop = true;
      for (boolean stop = false; stop != true;)
      {
         int array [] = new int [100];
         if (inStop == true)
         {
            System.out.println("point 5");
            System.out.print("Input: ");
            uInput = input.nextLine(); //reads user input
         }
         try //empty input repeater
         {
            System.out.println("point 1");
            try   //dealing with letters in string instead of numbers
            {
               System.out.println("point 2");

               temp = Integer.parseInt(uInput); //converts string to int
               array[count] = temp;
               count++;
               System.out.println(inStop);
               if (inStop == false) //executes when stop has been reached
               {
                  System.out.println("point 3");
                  int numberArray [] = new int [count]; //fills final array
                  for (int i = 0; i < count; i++)
                  {
                     numberArray[i] = array[i];
                  }
                  for (a = 0; a < numberArray.length; a++)
                  {
                     total = total + numberArray[a];
                  }
                  total = total / a;
                  stop = true; //ends parent loop
               }
            }
            catch (NumberFormatException e) //catches letters in string and checks for stop
            {
               System.out.println("point 4");
               stopper = uInput.charAt(0);
               stopper = Character.toUpperCase(stopper);
               if (stopper == 'S')
               {
                  inStop = false;

                  System.out.println("point 6");
               }
            }
         }
         catch (StringIndexOutOfBoundsException e)
         {
         }
      }
      System.out.println("The average of the values entered is: " + total + ".");
   }
}

The problem is, as you can see there are numerous numbered printouts that indicate (to me) where the program is at the moment. 问题是,正如您所看到的那样,有许多带编号的打印输出(对我而言)指示该程序当前所在的位置。 All runs fine, except for point 3. Point 3 for some reason doesn't execute whatsoever. 除第3点外,其他所有程序运行正常。第3点由于某种原因未执行。 No matter what I do. 不管我做什么。 Now, the problem lies on line 34, temp = Integer.valueOf(uInput); //converts string to int 现在,问题出在第34行, temp = Integer.valueOf(uInput); //converts string to int temp = Integer.valueOf(uInput); //converts string to int If I put in a print function directly after that line, that position doesn't print onto the screen. temp = Integer.valueOf(uInput); //converts string to int如果我在该行之后直接插入打印函数,则该位置不会打印到屏幕上。 I believe there are no syntax or logic errors with that part, and so does my lecturer, however the code still doesn't execute and the program loops infinitely afterwards. 我相信该部分没有语法或逻辑错误,我的讲师也没有,但是代码仍然无法执行,并且程序随后无限循环。 Something is breaking either temp or uInput in that line and we cannot figure out what. 某一行中断了temp或uInput,我们无法弄清楚是什么。 I have compiled and ran the code through a different compiler to what I initially used and even tried in the Command Prompt with the same results (so it is not the IDE causing the issue). 我已经使用与最初使用的编译器不同的编译器编译并运行了代码,甚至在命令提示符中尝试了相同的结果(因此不是由IDE引起问题)。

Any insight we may have missed would be appreciated. 我们可能错过的任何见解将不胜感激。 Thanks. 谢谢。

ps: don't knock my lecturer, he didn't write the code, and it isn't that easily readable. ps:请不要敲我的讲师,他没有写代码,而且它也不容易阅读。 He could easily know what the problem is, if not for any error in my explanations or his interpretations of how my program is meant to run. 如果我的解释或他对我的程序的运行方式的解释没有错误,他可以很容易地知道问题出在哪里。

I think that the reason you are having a problem identifying the issue is because of your code structure. 我认为您在确定问题时遇到问题的原因是由于您的代码结构。

You have mixed the logic for informing the use, with the logic for reading the inputs, and calculating. 您已经将告知使用的逻辑与读取输入并进行计算的逻辑混合在一起。

If your main method only deal with informing the user, and relies on another method to calculate the average,and another to read the user's input everything will be easier to read, follow and see that you are parsing "stop" as an int. 如果您的主要方法仅处理通知用户的问题,并依靠另一种方法来计算平均值,而另一种方法则是读取用户的输入,则所有内容都将更易于阅读,理解并看到您将“ stop”解析为一个int。

public static void main(String[] args) {
    System.out.println("instructions");
    int[] all = readUserInputs();
    double ave = calculateAverage(all);
    System.out.println("message " + ave);
}

private static double calculateAverage(int[] numbers) {
    // I will leave it to you to fill this out
    return yourValue;
}

private static String readUserInputs() {
    Scanner input;// as above
    int[] values; // is an array best? What about a List?
    for (int i = 0; ; i++) {
        String line = input.nextLine();
        if ("stop".equals(line) {
            break;
        }
        //try to parse and put into array/list
    }
    return values;
}

Hopefully you will find this easier to read and work with,I have left a few gaps for you to fill in. 希望您会发现它更易于阅读和使用,我为您留出了一些空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM