Не могу понять, почему программа не работает должным образом

Я пытался заставить эту программу работать, которая должна продолжать принимать данные от пользователя до тех пор, пока не будет введено -1 и вычислена сумма. Проблема заключается в следующем: разработайте и реализуйте программу Java (назовите ее InputSum ), которая предлагает пользователю ввести положительное целое число. Программа должна принимать целые числа до тех пор, пока пользователь не введет значение -1 (отрицательное). После того, как пользователь введет -1, программа должна отобразить введенные числа, за которыми следует их сумма, как показано ниже. Обратите внимание, что -1 не является частью вывода. Убедитесь, что программа проверяет каждое введенное число перед его обработкой, так как пользователь может вводить отрицательные числа, отличные от сентенциального значения -1.
Разработайте свою программу таким образом, чтобы она позволяла пользователю повторно запускать программу с другим набором значений. входы в том же цикле, как показано выше. Документируйте свой код, организуйте и разместите выходные данные, как показано выше.

Вот мой код:

/* Class:        CS1301
* Section:       9:30
* Term:          Fall 2015
* Name:          Matthew Woolridge
* Instructor:    Mr. Robert Thorsen
* Assignment:    Assignment 6
* Program:       1
* ProgramName:   InputSum
* Purpose:       The program prompts the user to input numbers until -1 is entered and calculates the sum
* Operation:     The information is statically instantiated in the code and
*                the data is output to the screen.
* Input(s):      The input is the numbers
* Output(s):     The output will be the sum of the numbers
* Methodology:   The program will use loops to determine if numbers or still to be entered or if -1 was entered
*
*/

import java.util.*;
import java.io.*;
public class InputSum
{

   public static void main (String[] args)
   {

      /******************************************************************************
      *                          Declarations Section                               *
      ******************************************************************************/
      /****************************CONSTANTS********************************/
      Scanner scan = new Scanner(System.in); //Initializes scanner

      int n = 1;
      int [] num = new int[n]; //Creates array for input numbers
      int i;
      int sum=0;

      /******************************************************************************
      *                             Inputs Section                                  *
      ******************************************************************************/

      System.out.print("Please input integers, note that -1 ends the submissions: "); //Prompts the user for input

     /****************************variables********************************/
     //***************************Calculations in processing************************//
     /******************************************************************************
      *                             Processing Section                            *
      ******************************************************************************/
      for(i=0; i<num.length; i++)
      {
         num[i] = scan.nextInt(); //Continues to read numbers and add them to the sum
         n = n + 1; //Adds to the array maximum
         sum = sum + num[i]; //Calculates the sum
         if (num[i] == -1){
            break;
         }
      }
      System.out.print("The numbers entered are: " + num[i]);
      System.out.print("\nThe sum of the numbers is: " + sum);

      /******************************************************************************
       *                              Outputs Section                                *
       ******************************************************************************/
       //***************Output is in the processing**************************//
   }
}

Проблема в том, что программа постоянно зависает на строке, где должна быть напечатана сумма. Любая помощь приветствуется!


person snipem1438    schedule 30.09.2015    source источник
comment
Ваша программа зависает, потому что размер вашего массива равен «1», поэтому она может принимать значения только для num[0].   -  person burglarhobbit    schedule 01.10.2015
comment
Поскольку вы не знаете, сколько значений вводит пользователь, использование массива является плохим выбором. Используйте некоторую структуру данных, которая расширяется по мере необходимости. Например. ArrayList должен соответствовать вашим потребностям.   -  person Matthias Wimmer    schedule 01.10.2015
comment
Как мне использовать arraylist, честно говоря, мне не приходилось использовать его так часто.   -  person snipem1438    schedule 01.10.2015


Ответы (2)


Вы можете использовать список для хранения чисел и бесконечный цикл, чтобы продолжать получать входные данные от пользователя. Также вы должны проверить условие остановки перед началом обработки чисел (поскольку в вашем вопросе упоминается, что -1 не является частью вывода). Вот иллюстрация

import java.util.*;
import java.io.*;
public class InputSum
{

   public static void main (String[] args)
   {

      /******************************************************************************
      *                          Declarations Section                               *
      ******************************************************************************/
      /****************************CONSTANTS********************************/
      Scanner scan = new Scanner(System.in); //Initializes scanner
      int number; //Declare a variable that will hold the temporal value that is read on the input stream      
      int sum=0;

      // Use a List 
      List<Integer> numbers = new ArrayList<Integer>();

      /******************************************************************************
      *                             Inputs Section                                  *
      ******************************************************************************/

      System.out.print("Please input integers, note that -1 ends the submissions: "); //Prompts the user for input

     /****************************variables********************************/
     //***************************Calculations in processing************************//
     /******************************************************************************
      *                             Processing Section                            *
      ******************************************************************************/
      // use an infinite loop
      for(; ; )
      {


         // You should normally do this check when you enter the loop
         // so that -1 which is a stop token should not be added to the list
         // and not taken into account in the sum


         number = scan.nextInt(); //Continues to read numbers and add them to the sum
         if (number == -1){
              break;
         }

         // You could write numbers.add(number) which would be
         // Java's autoboxing feature, but this is what would really take place
         numbers.add(Integer.valueOf(number));
         sum += number; //Calculates the sum


      }
      System.out.print("The numbers entered are: " + numbers);
      System.out.print("\nThe sum of the numbers is: " + sum);

      /******************************************************************************
       *                              Outputs Section                                *
       ******************************************************************************/
       //***************Output is in the processing**************************//
   }
}
person alainlompo    schedule 01.10.2015
comment
Спасибо всем за помощь и спасибо alainlompo за пример списка! :D - person snipem1438; 01.10.2015

Вместо использования массивов (поскольку это ограничивает количество входных данных) вы можете использовать временную переменную, которая будет вычислять значение суммы. Например, как показано ниже:

int sum=0;
int num=0;
while(num != -1) {
    sum = sum + num;
    num = scan.nextInt(); //note that the variables can be reused
}
person burglarhobbit    schedule 30.09.2015