提问者:小点点

一种不断要求输入整数直到输入一个非整数的程序。它打印所有输入整数的总和以及尝试次数


这是我发现的一个编码挑战网站的问题。这是我的代码:

我需要做什么或改变什么来获得想要的输出。

import java.util.Scanner; 
   public class CopyOfInputLoop { 
        public static void main (String[] args)  { 
        Scanner scan = new Scanner(System.in); 
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return."); 
    
    //placeholder variables that change as user inputs values
    int attempts = 0;
    int values = 0;
    int total = 0;
    
    //adds the values input by the user and continues asking for an integer if another integer is input  
    while (scan.hasNextInt()) { 
        total += values;
        values = scan.nextInt(); 
        System.out.println("Enter an integer to continue or a non-integer value to finish. Then press return.");  
        attempts += 1;
    } 
    
    //ends the program when a non-integer is input and prints the number of attempts and the sum of all values
    String input = scan.next();      
    System.out.println ("You entered " + input + "!"); 
    System.out.println ("You had " + attempts + " attempts!"); 
    System.out.println("The sum of all your values is " + total);
} 

}


共1个答案

匿名用户

试试这个。

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in); 
    System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
    
    //placeholder variables that change as user inputs values
    int attempts = 0;
    String value;
    int total = 0;
    
    //adds the values input by the user and continues asking for an integer if another integer is input  
    for (;;) {

      value = scan.next();

      try {

        total += Integer.valueOf(value);
         attempts++;
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return."); 
            
      } 
        
      //ends the program when a non-integer is input and prints the number of attempts and the sum of all values
      catch (Exception e) {

        attempts++;
        System.out.println ("You entered " + value + "!"); 
        System.out.println ("You had " + attempts + " attempts!"); 
        System.out.println("The sum of all your values is " + total + "!");
        break;

      }
    }
    scan.close();
  }
}