而Loop不是整数

时间:2014-02-19 20:27:52

标签: java java.util.scanner

我已创建此代码以获取无限的整数值,存储它们并计算平均值。它也以平方格式进行。我的问题是,我创建了它,以便while循环仅在输入数字0时停止。但是,我只是把它作为替代品,因为这是我可以测试其余代码以确保一切正常工作的唯一方法。

我真正想要做的是让while循环继续,直到用户提供非整数的输入。我尝试了所有内容,使用hasNextint()nextint等等,我该怎么办?

import java.io.*;
import java.util.*;

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

    Scanner TextIO = new Scanner(System.in);
    int inputNumber;     // One of the integers input by the user.
    int sum;             // The sum of all the integers.
    int count;           // The number of integers that have been entered.
    double mean;         // The mean value of the integers, rounded to 2 decimal places.
    int squarein;        // Value of squared number.
    int sumsquare;       // The sum of the squares of all the integers.
    double meansquare;   // The mean value of the squares of integers, rounded to 2 decimal places.

    /* Initialize the summation and counting variables. */
    sum = 0;
    count = 0;
    sumsquare = 0;
    meansquare = 0;

    /* Read and process the user's input. */
    System.out.println("Enter your first positive integer: ");
    inputNumber = TextIO.nextInt();

    while (inputNumber != 0) {
      sum += inputNumber;   // Add inputNumber to running sum.
      squarein =  inputNumber; //
      sumsquare = squarein * squarein; //square inputs
      count++;              // Count the input by adding 1 to count.
      System.out.println("Enter your next positive integer, or 0 to end: ");
      inputNumber = TextIO.nextInt();
    }

    /* Display the result. */
    if (count == 0) {
      System.out.println("You didn't enter any data!");
    } else {
      mean = ((double)sum) / count;
      meansquare = ((double)sumsquare) / count;

      TextIO.nextInt();

      System.out.println("Numbers entered: " + count + "\n");
      System.out.println("Sum: " + sum + "\n");
      System.out.println("Mean: " + mean + "\n");
      System.out.println("Sum Squares: " + sumsquare + "\n");
      System.out.println("Mean Square: " + meansquare + "\n");
    }
  } // end main()
} // end class InputStats

5 个答案:

答案 0 :(得分:0)

hasNextInt()应该有效

while(TextIO.hasNextInt()) {
   inputNumber = TextIO.nextInt();
   sum += inputNumber;
   squarein = inputNumber;
   sumsquare = squarein*squarein;
   count++;
   System.out.println("Enter your next positive integer: ");
}

另一件事,为什么在System.outs之前调用TextIO.nextInt()?它似乎没有必要,可能会抛出错误。

答案 1 :(得分:0)

使用布尔标志。最初将其设置为false,当用户输入时将其设置为true。

boolean userInputted = false;

while (!userInputted) {
.
.
.
// if user has inputted
    userInputted = true;
}

答案 2 :(得分:0)

您应该以字符串形式读取值,然后使用Integer.parseInt(string)将它们转换为整数;

这样你可以使用以下函数来检查它们是否是整数

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}

您的程序将如下所示:

import java.io.*;
import java.util.*;

public class InputStats {
    // *** I added this to help your while loop ***
    public static boolean isInteger(String s) {
        // check if a string is an integer, eg "10" is 10 but "w" is not an int
        try { 
            Integer.parseInt(s); 
        } catch(NumberFormatException e) { 
            return false; 
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner TextIO = new Scanner(System.in);

        // *** I added this to store the input as a string first ***
        String input;        // The original string inputted by the user

        int inputNumber;     
        int sum;             
        int count;           
        double mean;         
        int squarein;        
        int sumsquare;       
        double meansquare;   

        sum = 0;
        count = 0;
        sumsquare = 0;
        meansquare = 0;

        System.out.println("Enter your first positive integer: ");

        // *** I changed this to .nextLine(); to get a string ***
        input = TextIO.nextLine();

        // *** I made this while it's an integer so it stops when it's a string ***
        while (isInteger(input)) {
            inputNumber = Integer.parseInt(input);
            sum += inputNumber;
            squarein =  inputNumber; 
            sumsquare = squarein * squarein; 
            count++;              
            System.out.println("Enter your next positive integer, or a non integer to end: ");

            // *** I changed this to .nextLine(); to get a string ***
            input = TextIO.nextLine();
        }

        if (count == 0) {
            System.out.println("You didn't enter any data!");
        }
        else {
            mean = ((double)sum) / count;
            meansquare = ((double)sumsquare) / count;

            // *** I removed this because it was no longer needed *** TextIO.nextInt();

            System.out.println("Numbers entered: " + count + "\n");
            System.out.println("Sum: " + sum + "\n");
            System.out.println("Mean: " + mean + "\n");
            System.out.println("Sum Squares: " + sumsquare + "\n");
            System.out.println("Mean Square: " + meansquare + "\n");
        }

    } // end main()

} // end class InputStats

答案 3 :(得分:0)

您可以让用户输入一行文本,其中数字用逗号分隔,并使用.split(",")分隔成一个字符串数组,然后通过.length循环遍历该数组并应用{{1每个字符串删除尾随空格,然后使用.trim()将字符串转换为整数。显然,如果用户输入格式错误的数据,请将其全部放在Integer.parseInt(strarray[i])中。

答案 4 :(得分:0)

您需要的是一种判断用户输入的数字是数字还是其他内容的方法。 尝试这样的功能。

    //Function to parse the input from provided scanner, and return null 
    //if input is not a number
    public static Integer parsedInputFrom(Scanner sc){
       String input= sc.next();
       Integer inputNumber=null;
       try{
              inputNumber = Integer.parseInt(input);
       } catch (NumberFormatException n){
           return null;
       }
       return inputNumber;
    }