Wie kann ich die Variable in der Try Catch returnen?

yachty66

Mitglied
public class Console3 {

static final Scanner in = new Scanner(System.in);
//private static int num;

static public int readIntegerFromStdIn(String text) {
while ( true ) {
try {
System.out.print(text + " ");
int num = in.nextInt();
break;
} catch(InputMismatchException e) {
System.out.println(text + " ");
String errStr = in.next();
}
}
return num;

}


Der return Befehl von Num zeigt mir eine Fehlermeldung an, denn "int num" wird nur innerhalb von der try catch Methode gespeichert. Jetzt ist die Frage, wie ich den Wert der in "int num" gespeichert ist returnen kann?
 
Du kannst einfach das return an die Stelle des break setzen, dann hast Du die Rückgabe.
Oder Du kannst die Deklaration der Variable vor die while Schleife setzen.
 
Java:
    @SuppressWarnings("resource")
    public static int readIntegerFromStdIn(String text) {
        int num = 0;
        for (boolean cont = true; cont;) {
            try {
                System.out.print(text + " ");
                num = new Scanner(System.in).nextInt();
                cont = false;
            } catch (InputMismatchException e) {
                InputMismatchException e2 = new InputMismatchException("int expected, but input was something other");
                System.out.println(e2.getMessage());
            }
        }
        return num;
    }

    public static void main(String[] args) {
        System.out.println(readIntegerFromStdIn("Bitte Zahl:"));
    }

Oder so
Java:
    public static int readIntegerFromStdIn(String text) {
        int num = 0;
        Scanner s = null;
        for (boolean cont = true; cont;) {
            try {
                System.out.print(text + " ");
                s = new Scanner(System.in);
                num = s.nextInt();
                cont = false;
            } catch (InputMismatchException e) {
                InputMismatchException e2 = new InputMismatchException("int expected, but input was: " + s.next());
                System.out.println(e2.getMessage());
            }
        }
        return num;
    }
 
Zuletzt bearbeitet von einem Moderator:

Zurück
Oben