Z
zuepse
Gast
Das nachstehende Programm läuft soweit einwandfrei - Entsprechend einer Hausaufgabengestellung mit entsprechenden Bedingungen programmiert.
Dennoch wird bei einem Zwangsabbruch (Eclipse Terminate Button) vom input.nextLine() eine Exception geworfen (NoSuchElementException - No Line found).
Nun habe ich diesbezüglich eine Verständnisfrage, wird die Exception geworfen, da das Programm zwangsweise beendet wird und nextLine() keinen Inhalt findet? Kann ich das irgendwie verhindern, ist das "normal" ?
Dennoch wird bei einem Zwangsabbruch (Eclipse Terminate Button) vom input.nextLine() eine Exception geworfen (NoSuchElementException - No Line found).
Nun habe ich diesbezüglich eine Verständnisfrage, wird die Exception geworfen, da das Programm zwangsweise beendet wird und nextLine() keinen Inhalt findet? Kann ich das irgendwie verhindern, ist das "normal" ?
Java:
import java.util.Scanner;
import java.util.InputMismatchException;
@SuppressWarnings("serial")
class ZeroDivisorException extends Exception
{
public ZeroDivisorException() {}
public ZeroDivisorException(String s)
{
super(s);
}
}
@SuppressWarnings("serial")
class InvalidOperatorException extends Exception
{
public InvalidOperatorException() {}
public InvalidOperatorException(String s)
{
super(s);
}
}
public class Calculator
{
public static void main(String[] args)
{
char operator = ' ';
String eingabe;
int ergebnis = 0, operand = 0;
boolean exit = false;
Scanner input = new Scanner(System.in);
System.out.println("Taschenrechner - Operationen +-*/");
while (!exit)
{
try
{
System.out.println("Ergebnis: " + ergebnis);
eingabe = input.nextLine();
operator = eingabe.charAt(0);
if(operator == 'e' & eingabe.length() == 1) // Programm beenden
exit = true;
if(operator == 'c' & eingabe.length() == 1) // Ergebnis zuruecksetzen
ergebnis = 0;
if(eingabe.length() == 1) // Sonstige Exception
if(operator != 'e' & operator != 'c')
throw new Exception();
if(eingabe.length() > 1)
{
Scanner inputop = new Scanner(eingabe.substring(1));
operand = inputop.nextInt();
switch(operator)
{
case '+': ergebnis = ergebnis + operand;
break;
case '-': ergebnis = ergebnis - operand;
break;
case '*': ergebnis = ergebnis * operand;
break;
case '/': if(operand != 0)
{
ergebnis = ergebnis / operand;
}
else
{
throw new ZeroDivisorException("Division durch 0");
}
break;
default: throw new InvalidOperatorException("Unbekannter Operator");
}
}
}
catch (InputMismatchException exc)
{
System.out.println("ist keine Ganzzahl! -- nochmal:");
}
catch (ZeroDivisorException exc)
{
System.out.println("Handler für ZeroDivisorException: behandelt " + exc.getMessage());
}
catch (InvalidOperatorException exc)
{
System.out.println("Handler für InvalidOperatorException: behandelt " + exc.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
}