Home > Mobile >  everytime my input is numbers with commas like 3,14 or 15.05 it throws an exception but does not wri
everytime my input is numbers with commas like 3,14 or 15.05 it throws an exception but does not wri

Time:11-02

As said, my code does not accept non-whole numbers, which is the point of the program, but it throws exception instead of getting to the else statement

import java.util.Scanner;

public class Minimum {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        
        int zahl1;
        int zahl2;
        int zahl3;
        
        System.out.print("Bitte geben Sie drei Zahlen ! ");
        zahl1 = keyboard.nextInt();
        zahl2 = keyboard.nextInt();
        zahl3 = keyboard.nextInt();
        
        int[] zahlen = new int[] { zahl1, zahl2, zahl3 };
        
        if (zahl1 % 1 == 0 && zahl2 % 1 == 0 && zahl3 % 1 == 0) {   
            int min = getMin(zahlen);
            System.out.println("Minimum ist : "  min);
        } else {
            System.out.println("Die angegebene Zahl ist ungültig !!");
            // this statement does not show up when I enter a non whole number
        } // end if-else
    } // end main


    private static int getMin(int[] zahlen) {       
            
        int minimum = zahlen[0]; 
        for (int i = 0; i < zahlen.length; i  ) { 
            int zahl = zahlen[i];
            
            if (zahl < minimum) { 
                minimum = zahlen[i]; 
            } // end if
        } // end for
            
        return minimum;         
    } // end getMin
}

CodePudding user response:

The main problem is you are using int which stands for integer = only full numbers such as 1, 5, 7. If you want to use decimals you need float/double.

CodePudding user response:

If a non-integer is expected in the input, related variables need to be declared as double and accordingly they are read using keyboard.nextDouble().
After that you may validate if these numbers are integer, and print a message.

Updated code of main method may look as follows:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    
    System.out.print("Bitte geben Sie drei Zahlen ! ");

    double zahl1 = keyboard.nextDouble();
    double zahl2 = keyboard.nextDouble();
    double zahl3 = keyboard.nextDouble();
    
    if (zahl1 % 1 == 0 && zahl2 % 1 == 0 && zahl3 % 1 == 0) {
        int[] zahlen = {(int) zahl1, (int) zahl2, (int) zahl3};
        int min = getMin(zahlen);
        System.out.println("Minimum ist : "  min);
    } else {
        System.out.println("Die angegebene Zahl ist ungültig !!");
        // this statement does not show up when I enter a non whole number
    } // end if-else
} // end main
  • Related