Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

java - Parsing Ints to Strings from Scanner in Try Catch

I've been given a task that I have to create a Shopping List program. I've done this in Python, and it was relatively straight forward. However, in Java I've hit a bit of a roadblock.

These are my variables, I am aware of the issues with using statics in this way and that it would be best to avoid doing it.

private static Scanner input = new Scanner(System.in);
private static String list_add = "string"; //"string" is just a place holder
private static ArrayList listFull = new ArrayList();
private static ArrayList listPos = new ArrayList();
private static int userIn = 1; //1 is also being used as place holder

Which I use in:

private static void userInput() {
    boolean isValid = false;

    while (!isValid) {
        isValid = true;
        try {
            userIn=Integer.parseInt(input.next());
        }
        catch (InputMismatchException e) {
            System.out.println("That's not a valid number!");
            isValid = false;
        }
    }

}

The reasoning behind doing it this way is the less one needs to type the quicker the task can be completed. Which was working as nice philosophy up until I tried this. My previous attempt to solve this problem gave an infinite loop, and the second solution that came to mind returned a StackOverflowError. When I asked about avoiding the infinite loop, I was directed to another question (Endless loop while using "try and catch " block inside a "while loop") which I did not believe helpful to begin with, however found that it was (Thank you whoever marked that). I didn't get this solution to work, however, and I cannot see where I went wrong.

After trying different inputs to see if their was one specific type that killed it, these were the errors I received:

Test Case "strin":

Exception in thread "main" java.lang.NumberFormatException: For input string: "strin"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at DebuggingMethods.AllIn(DebuggingMethods.java:17)
    at DebuggingMethods.Menu(DebuggingMethods.java:33)
    at DebuggingMethods.main(DebuggingMethods.java:58)

Test Case "Ten":

Exception in thread "main" java.lang.NumberFormatException: For input string: "Ten"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at DebuggingMethods.AllIn(DebuggingMethods.java:17)
    at DebuggingMethods.Menu(DebuggingMethods.java:33)
    at DebuggingMethods.main(DebuggingMethods.java:58)

Test Case int(10):

Which ran with the anticipated outcome.

I had thought that I was missing a module, so I did import java.lang.*; which did not change the error. If someone has a solution, please help me out. I can't find a question that already posted that explains what I am doing wrong. When I pulled it out of the Try-Catch it was working kind of.


Full Piece

import java.util.InputMismatchException;
import java.util.*;
import java.util.Scanner;
import java.lang.*;

public class TestOne {

    private static Scanner input = new Scanner(System.in);
    private static String list_add = "string";
    private static ArrayList listFull = new ArrayList();
    private static ArrayList listPos = new ArrayList();
    private static int userIn = 1;

    private static void userInput() {
        boolean isValid = false;

        while (!isValid) {
            isValid = true;
            try {
                userIn=Integer.parseInt(input.next());
            }
            catch (InputMismatchException e) {
                System.out.println("That's not a valid number!");
                isValid = false;
            }
        }

    }


    public static void main(String[] args) {
        //titleMain();
        userInput(); // For the sake of demonstration


    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've got your exceptions mixed up. You're catching an InputMismatchException, which is what input.nextInt() would have thrown if the input were invalid. But you're actually using Integer.parseInt to parse the input, which throws NumberFormatException in case of invalid input. And since NumberFormatException isn't a subclass of InputMismatchException, it isn't caught and you end up dying with a stack trace.

You don't actually need to do anything with exception at all here. The Scanner can tell you if the next input is a valid integer or not and you can then actively decide what do about it. Think along these lines:

Scanner sc;
//...
System.out.println("Please enter a number");
while (!sc.hasNextInt()){
    sc.nextLine();  // throw away the bad input
    System.out.println("Please enter a valid number");
}
int theNum = sc.nextInt();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...