简体   繁体   English

如何验证以便用户只输入整数

[英]How to I validate so the user only enters integers

Iv'e been trying to get my code to work so that the user can only input integers.我一直试图让我的代码工作,以便用户只能输入整数。 However, its keeps crashing when I enter something with characters like "awsd".但是,当我输入带有“awsd”等字符的内容时,它会一直崩溃。 I've tried using a bool to help, but it only catches negative inputs.我尝试使用 bool 来提供帮助,但它只捕获负面输入。 Also, the input method must start as an integer, so I cant switch it to a string.此外,输入法必须以 integer 开头,所以我无法将其切换为字符串。 Please help.请帮忙。

import java.util.Scanner;   // Needed for Scanner class
import java.io.*;           // Needed for File I/O classes

public class Reverse {
    public static void main(String[] args) throws IOException {
        Scanner keyboard = new Scanner(System.in);
        String Continue = "yes";
        int num;

        //creates the file name
        File fileWR = new File("outDataFile.txt");
        //creates the file object
        fileWR.createNewFile();
        //file scanner
        BufferedWriter output = new BufferedWriter(new FileWriter(fileWR, true));

        while (Continue.equals("yes")) {
            System.out.print("Enter an integer number greater than 0 :");
            num = keyboard.nextInt();
            keyboard.nextLine();
                if (fileWR.exists())
                {
                    validate(num, output);
                }
                else
                {
                    fileWR.createNewFile();
                }

                //option if the user wants to continue
                System.out.println("Do you wish to continue?(yes or no): ");
                Continue = keyboard.nextLine();
            }
        output.close();
    }


    public static void validate(int num, BufferedWriter output) throws IOException {
        Scanner keyboard = new Scanner(System.in);
        while(!checkNum(num))
        {
            System.out.print("That is not an integer greater than 0, please try again: ");
            num = keyboard.nextInt();
            keyboard.nextLine();
        }
        System.out.print("The original numbers are " + num +"\n");
        output.write("\r\nThe original numbers are " + num +"\r\n");
        reverse (num, output);
        even (num, output);
        odd(num, output);

    }// end of public static void validate

    public static void reverse(int num, BufferedWriter output) throws IOException {                                                                                                         
        String input = String.valueOf(num);         //must output result within the void method for it to count as a void method
        String result = "";                         //otherwise, you cannot output it in the main method.

        for (int i = (input.length() - 1); i >= 0; i--) 
           {
               result = result + input.charAt(i)+' ';
           }
           result = "the number reversed "+ result +"\r\n";
           System.out.print(result);
           output.write(result);
    }// end of public static void reverse

    public static void even(int num, BufferedWriter output) throws IOException {
        String input = String.valueOf(num);
        String result = "";

           for (int i = 0; (i < input.length()); i++) 
           {
               if (Character.getNumericValue(input.charAt(i)) % 2 == 0) 
                   result = result + input.charAt(i) + ' ';
           }
           if (result == "") {
               result = "There are no even digits" + "\r\n";
           } else {
               result = "the even digits are "+ result +"\r\n";
           }
           System.out.print(result);
           output.write(result);
    }// end of public static void even

    public static void odd(int num, BufferedWriter output) throws IOException {
        String input = String.valueOf(num);
        String result = "";

           for (int i = 0; (i < input.length()); i++) 
           {
               if (Character.getNumericValue(input.charAt(i)) % 2 == 1)
               {
                   result = result + input.charAt(i) + ' ';
               }
           }
           if (result == "") {
               result = "There are no odd digits" + "\r\n";
           } else {
               result = "the even odd digits are "+ result +"\r\n";
           }
           System.out.print(result);
           output.write(result);
           System.out.print("------------------------\n");
           output.write("------------------------\n");

    }// end of public static void odd
    public static boolean checkNum(int num)
    {
        if(num > 0) {
            return true;
        }
        else {
            return false;
        }

    }
}

You should first get the String, and then try to cast it:您应该首先获取字符串,然后尝试转换它:

try {
    String numStr = keyboard.nextLine();
    num = Integer.parseInt(numStr);
    //Complete with your code
} catch (NumberFormatException ex) {
    System.out.print("That is not an integer");
}

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

相关问题 如何验证用户在 java 中输入的数据 - how do I validate a data that user enters in java 如何确保用户仅输入0到10之间的数字? - How do I make sure that the user enters a number between 0 and 10 only? 仅当用户输入某些值时,如何使程序继续运行? - How do I make my program continue only if the user enters certain values? 如果用户输入带字符串的int,则Onclick会验证edittext - Onclick validate edittext if user enters an int with a string 当用户在Java中的控制台上输入字符时,如何只处理单个字符 - How to process only single charater as and when user enters it on the console in java Integers.parseint(在扫描仪输入上),我也想进行限制,因此用户只能输入0到100范围内的数字 - Integers.parseint( on scanner input ), also i want to make limits so user can only input number in range from 0 to 100 如何确保用户输入有效选项? - How can I ensure user enters a valid choice? Java-如果用户输入无效的输入,如何返回异常? - Java - How would I return an exception if the user enters a invalid input? 如何根据用户输入的经度和纬度找到位置? - How do I find a location based on the longitude and latitude that the user enters? 用户输入null时如何退出循环 - How do i exit a loop when user enters null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM