0 Daumen
183 Aufrufe

Hey Leute

und zwar hab ich die Aufgabe mit Java etwas zu programmieren, dass eine Zahl per Kommandozeile einliest und dann guckt ob es kleiner oder größer als zehn ist oder ob es überhaupt eine zahl ist. Dabei soll ich mit try-catch exception arbeiten. Das ist dabei rausgekommen. Mein Problem ist nun selbst wenn ich 1 eingebe kommt die Meldung "Zahl darf nicht größer als zehn sein".



public class excep {

public static void main(String[] args) throws Exception {



int zahl = 0;
          try {
          if ( zahl > 10) {}
          zahl = Integer.parseInt(args[0]);
         
          throw new Exception("Zahl darf nicht größer als 10 sein!");
          } catch (ArrayIndexOutOfBoundsException e) {
              System.out.println( "Bitte gib ein Argument" );
              zahl = 2;
              e.printStackTrace();
          } catch (NumberFormatException f) {
          System.out.println("bitte gib eine Zahl ein");
          zahl = 3;
          f.printStackTrace();
         
}
          System.out.println(zahl);
}


}

Avatar von

1 Antwort

0 Daumen
 
Beste Antwort
Mein Problem ist nun selbst wenn ich 1 eingebe kommt die Meldung "Zahl darf nicht größer als zehn sein

Das liegt daran, dass du hier

if (zahl > 10) {}
zahl = Integer.parseInt(args[0]);
         
throw new Exception("Zahl darf nicht größer als 10 sein!");

die Exception nicht in den {} der if-Bedingung wirfst, die Exception wird also immer geworfen.

Außerdem sollte das parsen des Integer Wertes vor der if-Bedingung passieren.


Code:

public class Excep {

public static void main(String[] args) throws Exception {
int zahl;
try {
zahl = Integer.parseInt(args[0]);

if (zahl > 10) {
throw new Exception("Zahl darf nicht größer als 10 sein!");
}

if (zahl < 10) {
throw new Exception("Zahl darf nicht kleiner als 10 sein!");
}

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bitte gib ein Argument!");
zahl = 2;
e.printStackTrace();

} catch (NumberFormatException f) {
System.out.println("bitte gib eine Zahl ein!");
zahl = 3;
f.printStackTrace();

} catch (Exception g) {
System.out.println("Zahl darf nicht größer oder kleiner als 10 sein!");
zahl = 4;
g.printStackTrace();
}


System.out.println(zahl);
}
}
Avatar von

Ein anderes Problem?

Stell deine Frage

Willkommen bei der Stacklounge! Stell deine Frage einfach und kostenlos

x
Made by a lovely community