I find it difficult to find information on how System.in.read(); works System.in.read(); maybe someone can help me. A scanner seems to be preferable, but I am not allowed to use it.
I was assigned a task in which I had to read the user input of the console in the form of Boolean-Operator-Boolean, for example. T ^ F or T & T via System.in.read() and just print what the operator returns.
Normal people are likely to use a different method, but the assignment specifically indicates that only System.in.read() and System.out.println() allowed.
Here is my attempt to solve it:
import java.io.*; public static void main(String[] args) { String error = "Reading error, please use T or F"; boolean a = true; //char: 84 or 116 for T and t boolean b = false; //char: 70 or 102 for F and f int userChar1; int userOperator; int userChar2; int chosenOperator = 0; try { //Get first char System.out.println("Enter the first value (T or F):"); userChar1 = System.in.read(); if((userChar1==84)||(userChar1==116)) { // T or t a = true; } else if ((userChar1==70)||(userChar1==102)) { // F or f a = false; } else { System.out.println(error); } //Get second char System.out.println("Select an operator: & | ^"); userOperator = System.in.read(); if(userOperator==38) { // & chosenOperator = 0; } else if (userOperator==124) { // | chosenOperator = 1; } else if (userOperator==94) { // ^ chosenOperator = 2; } else { System.out.println(error); } //Get third char System.out.println("Enter the second value:"); userChar2 = System.in.read(); System.in.close(); if((userChar2==84)||(userChar2==116)) { b = true; } else if ((userChar2==70)||(userChar2==102)) { b = false; } else { System.out.println(error); } //Figure out result boolean result; switch (chosenOperator) { case 0: result = a&b; case 1: result = a|b; case 2: result = a^b; System.out.println(result); } } catch(IOException e) { } }
The execution of this code causes the console to wait for user input after the first System.in.read() and checks that the char input is correct. After that, all subsequent System.in.read() ignored and the program terminates.
I found a piece of code that used System.in.close() , so I still donβt know which methods I spliced ββafter each System.in.read() . This causes the program to terminate when the first System.in.read() is called after.
So what exactly is going on? How do you use System.in.read() correctly?
source share