Java: Terminating the while loop after pressing "Q" key [duplicate] - java

This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 5 years ago.
I have this following java program which is working fine without while loop, but I want to run the execution until user pressed Q key from the keyboard.
So What condition should be put in while loop which breaks the loop?
import java.awt.event.KeyEvent;
import java.util.Scanner;
import static javafx.scene.input.KeyCode.Q;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(kbhit() != Q){
System.out.print("Input first binary number: ");
try{
String n = in.nextLine();
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}
Any help would be great.
Thank You.

I don't think you can use KeyEvent within a console application as there's no keyboard listener defined.
Try a do-while loop to watch for an input of the letter q. And you should compare strings using equals method
Scanner in = new Scanner(System.in);
String n;
System.out.print("Input first binary number: ");
do {
try{
n = in.nextLine();
// break early
if (n.equalsIgnoreCase("q")) break;
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
// Prompt again
System.out.print("Input binary number: ");
} while(!n.equalsIgnoreCase("q"));

What about this?
public class BinaryToDecimal {
public static void main(String[] args) {
System.out.print("Input first binary number: ");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
while(!"q".equalsIgnoreCase(line.trim())){
try{
System.out.println(Integer.parseInt(line,2));
System.out.print("Input next binary number: ");
line = in.nextLine();
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}

Related

using try catch in a while loop (java) [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 2 years ago.
I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
return 0;
}
}
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println(number);
} else {
System.err.println("Not a valid input. Error :" + sc.next());
}
}

I having problem getting input by scanner from java console [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I'm using on program that I need get input from console in java. here is a simple code only for showing you the problem.
public class Main {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
System.out.println();
}
}
for input :
"stackOverFlow"
12
3.4
out put is :
You entered string stackOverFlow
You entered integer 12
and out put should be :
You entered string stackOverFlow
You entered integer 12
You entered float 3.4
what is the problem why the last line don't be read by scanner ?
Scanner does not work like this. in.nextLine() will consume the whole line and wait for you to press return, and then call the next statement, which happens to be a print. Then, it expects you to enter an int, so on...
Your program would expect input as follows:
> stackOverFlow
You entered string stackOverFlow
> 12
You entered integer 12
> 3.4
You entered float 3.4
If you want to parse a String, int, and float from the first string a user enters, that is a different operation (assuming you enter some string that would be split into 3 elements by a space):
import java.util.Scanner;
public class Test {
static int i;
static float f;
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a: string int float");
String s = in.nextLine();
String[] split = s.split(" ");
String str = split[0];
try {
i = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
try {
f = Float.parseFloat(split[2]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("String: " + str);
System.out.println("Int: " + i);
System.out.println("Float: " + f);
in.close();
}
}

Why is this Scanner assigning null to a variable?

For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}

Java Scanner that takes only letters and spaces, but not space-only strings [duplicate]

This question already has answers here:
Scanner class skips over whitespace
(5 answers)
Closed 6 years ago.
I've done a simple program that allows user to enter a name and then greets him.
import java.util.Scanner;
public class nameinput {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a name: (only letters, at least 2 characters long)");
while (true) {
String name= sc.next();
if (name.length() < 2){
System.out.println("This name is too short!");
continue;
}
else if (!name.matches("[a-zA-Z]+")){
System.out.println("Letters only!");
continue;
}
else {
System.out.println("Hello, " + name);
break;
}
}
}
}
However I have two issues I can't solve:
When user inputs a name containing a space, it only gets what's before space.
When user passes only a series of spaces, or doesn't pass anything, nothing happens, like he didn't type anything. I'd the user to receive a proper message informing him that the spaces-only strings and empty strings are not allowed.
I hope I was clear in descriptions of problems, thanks in advance for any help!
If you just replace sc.next with sc.nextLine(). nextLine will capture all the key press until press enter.
import java.util.Scanner;
public class nameinput {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a name: (only letters, at least 2 characters long)");
while (true) {
String name= sc.nextLine();
if (name.length() < 2){
System.out.println("This name is too short!");
continue;
}
else if (!name.matches("[a-zA-Z]+")){
System.out.println("Letters only!");
continue;
}
else {
System.out.println("Hello, " + name);
break;
}
}
}
}

How to validate user's input, and read-in their input again if it invalidates, using try-catch?

I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);

Categories