3

I wrote a code which is kind of an interview. It asks you how old you are and what your gender is. For some reason the .exe gets terminated after it prints out the second question. Why is that? How can I fix it?

I checked the syntax but can't seem to find the mistake.

import java.io.IOException;

public class Abfrage {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    char Geschlecht;
    System.out.println("Wie ist dein Geschlecht? M oder W?");
    Geschlecht = (char) System.in.read();

    int Alter;
    System.out.println("Wie ist dein Alter?");
    Alter = (int) System.in.read();
    if (Alter >= 18 && Alter <= 100)
    {
        System.out.println("Du bist volljaehrig, herzlichen Glueckwunsch!");
    }
}

}

It prints out this string ("Wie ist dein Alter?") and after that it gets terminated. I can't put in my age(number) which is the question asked in the println.

I expect it to let me put in my age, and if I am between 18 and 100 it should tell me "congrats on being an adult." (its not finished there are more if/else)

Edit: I tried adding an if else statement. When I run the .exe:

    if (Alter >= 18 && Alter <= 100)
    {
        System.out.println("Du bist volljaehrig, herzlichen Glueckwunsch!");
    }
    else if (Alter >= 0 && Alter <= 17);
    {
        System.out.println("Du bist leider minderjaehrig mein Kind");
    }

When I did this, it just prints out the else if println "Du bist leider minderjaehrig mein Kind" after the question "Wie ist dein Alter?". It terminates after that.

Zabuzard
  • 20,717
  • 7
  • 45
  • 67
mcfadizzle
  • 33
  • 4
  • When you add an `else` block with a `System.out.println()` it it, does it gets executed? – Progman Apr 28 '19 at 12:29
  • I did try that, I edited my question you can see what happened when I did that. Thanks for the input. – mcfadizzle Apr 28 '19 at 12:42
  • Please add an `else` block without a condition and check if it gets executed. Output the value of `Alter` in that case to check what the actual value is inside the variable. – Progman Apr 28 '19 at 12:45

4 Answers4

8

Explanation

You likely entered more than just one character.

You clicked for example M for male but also hit the enter button. Your actual input is

M\n

and not just

M

and the first read reads the M while the second reads the \n without asking you for new input, since there is still some unread input left.

So Alter is the int value of the \n character and thus your if block is not entered. So the code executed fully.


Solution

There is a handy class which was developed exactly for the purpose to easy such input reading, Scanner (documentation).

Scanner scanner = new Scanner(System.in);
System.out.println("Wie ist dein Geschlecht? M oder W?");
String geschlecht = scanner.nextLine();

System.out.println("Wie ist dein Alter?");
int alter = Integer.parseInt(scanner.nextLine());
if (alter >= 18 && alter <= 100) {
    System.out.println("Du bist volljaehrig, herzlichen Glueckwunsch!");
}

Note

Be aware that the Java naming convention says camelCase for variable names, not PascalCase. So your Geschlecht and Alter should rather be called geschlecht and alter.

Also, you should create your variables at the exact position you need them, and not earlier. So instead of

char geschlecht;
System.out.println("Wie ist dein Geschlecht? M oder W?");
geschlecht = ...

prefer

System.out.println("Wie ist dein Geschlecht? M oder W?");
char geschlecht = ...

That will make your code easier to read.

Depending on your operating system, the newline character may not just be \n but can also be \n\r. Very cumbersome to handle this stuff yourself, Scanner will do all of that for you.

Zabuzard
  • 20,717
  • 7
  • 45
  • 67
  • Someone told me that in java I should always use uppercase letters, thats why I changed it. Thats good to know, I will keep it in mind. Thanks a lot. – mcfadizzle Apr 28 '19 at 12:47
  • When I tried using your scanner code, it tells me "Scanner cannot be resolved to a type" and also "sc" cannot be resolved aswell. Why is that? I havent used this scanner command yet, I am pretty new to this so sorry if this is a stupid question. – mcfadizzle Apr 28 '19 at 12:56
  • @mcfadizzle Heres a short overview of the naming convention: https://i.imgur.com/vpe0MgF.png. I had a typo, it should be `scanner`, not `sc`. Its the name of the scanner variable created in the beginning. You need to import every class you use (except its in the `java.lang` package or in the same you are currently in, since those two are auto-imported). So you need to write `import java.util.Scanner;` at the beginning of your program. – Zabuzard Apr 28 '19 at 13:03
  • 1
    ITS WORKING! Thanks a ton. I spent like 1 hour on this. – mcfadizzle Apr 28 '19 at 13:18
1

You're reading raw bytes with System.in.read(). You're probably pressing enter after your input, so Alter will contain the byte value of enter, which is the value 13, hence your if block never gets executed.

Don't read raw bytes, instead use a Scanner to get user input with nextLine().

import java.io.IOException;
import java.util.Scanner;

public class Abfrage {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Wie ist dein Geschlecht? M oder W?");
        String geschlecht = sc.nextLine();

        System.out.println("Wie ist dein Alter?");
        int alter = Integer.parseInt(sc.nextLine());
        if (alter >= 18 && alter <= 100)
        {
            System.out.println("Du bist volljaehrig, herzlichen Glueckwunsch!");
        }
    }
}
QBrute
  • 3,470
  • 6
  • 30
  • 36
1

Your issue here is that System.in keeps a special character (carriage return CR) from the last input that you given. Then, when you cast the input using (int), it gives your the character code of the carriage return (which is 13).

A fix here could be to use java.util.Scanner

Here is an example:

Scanner scanner = new Scanner(System.in);

char Geschlecht;
System.out.println("Wie ist dein Geschlecht? M oder W?");
Geschlecht = scanner.next().charAt(0);

// It clears the content by consuming \n
scanner.nextLine();

int Alter;
System.out.println("Wie ist dein Alter?");
Alter = scanner.nextInt();

However, this program is absolutly not idiot proof, it could throw exceptions if the user gives something else that what is expected.

nero
  • 383
  • 4
  • 11
0

System.in returns the InputStream, and the read method of its is called. JavaDocs states read:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

So, basically, you are getting the byte value parsed. Try to use scanner isntead as described here : How can I read input from the console using the Scanner class in Java?

anasmi
  • 2,302
  • 10
  • 24