Java: how to read an input int

折月煮酒 提交于 2019-12-23 23:09:15

问题


So, I was looking for an efficient way, using Java's standard packages, to read an input integer... For example, I came across the class "Scanner", but I found two main difficulties:

  1. if I don't insert an int, I'm not actually able to solve the exception;
  2. this class works with tokens, but my aim is to load the string in its full length.

This is an example of execution I would like to realize:

Integer: eight
Input error - Invalid value for an int.
Reinsert: 8 secondtoken
Input error - Invalid value for an int.
Reinsert: 8
8 + 7 = 15

And this is the (incorrect) code I tried to implement:

import java.util.Scanner;
import java.util.InputMismatchException;

class ReadInt{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        boolean check;
        int i = 0;
        System.out.print("Integer: ");
        do{
            check = true;
            try{
                i = in.nextInt();
            } catch (InputMismatchException e){
                System.err.println("Input error - Invalid value for an int.");
                System.out.print("Reinsert: ");
                check = false;
            }
        } while (!check);
        System.out.print(i + " + 7 = " + (i+7));
    }
}

回答1:


Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so ...

import java.io.*;

public class ReadInt{
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        boolean check;
        int i = 0;
        System.out.print("Integer: ");
        do{
            check = true;
            try{
                i = Integer.parseInt(in.readLine());
            } catch (NumberFormatException e){
                System.err.println("Input error - Invalid value for an int.");
                System.out.print("Reinsert: ");
                check = false;
            }
        } while (!check);
        System.out.print(i + " + 7 = " + (i+7));
    }
}



回答2:


To use with tokens:

int i = Integer.parseInt(in.next());

Then you could do:

int i;
while (true) {
    System.out.print("Enter a number: ");
    try {
        i = Integer.parseInt(in.next());
        break;
    } catch (NumberFormatException e) {
        System.out.println("Not a valid number");
    }
}
//do stuff with i

That above code works with tokens.



来源:https://stackoverflow.com/questions/14259508/java-how-to-read-an-input-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!