how to check if an input from a user is 1 integer - java

i am asking from the user to type a number and I need to check if the user's answer is only one integer
This is my code:
System.out.println("MENU:What do you want to do ? \n1.Buy a new ticket!\n2.Renewal of a ticket\n3.Update the content");
System.out.println("Type the number of what you want to do ");
if (!(input.hasNextInt() && input.hasNextByte())) { // if the input is not an integer and more than one byte
System.out.println("ERROR!!Enter an integer value ");
input.next();
} else {
int Read = input.nextInt(); //reads what the user has typed/given
System.out.println("You entered an integer value! ");
}
i have tried this, and it shows error (which menas it is working)for inputs like these: 34443 22123 cdsfr4d but when i give only 2 or 3 integers like: 34 or 567, it does not show me any error !HOw cam I cnage it in order to show me the correct message

Remove && input.hasNextByte()

I'm assuming you only want the user to input: 1, 2, or 3 since that's what I'm seeing in your Console menu.
The way I would handle this issue is by using a switch statement and a default case in case they enter anything else.
if (!(input.hasNextInt()) { // if the input is not an integer and more than one
System.out.println("ERROR!!Enter an integer value ");
input.next();
} else {
int choice = input.nextInt();
switch (choice) {
case 1: //If choice is 1
case 2: // If choice is 2
case 3: // If choice is 3
default: // If choice is any other integer
}
}
Switch statements are not commonly used in Java as there are usually better ways to handle these scenarios. Here's some more information on switch statements:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Welcome to the Stack Overflow community, make sure you use Google before you use Stack!

I am not sure what you want to do. But as per your approach it seems like you want to input a number through keyboard and want to check if it is a single digit number or not. If I am right then here we go.
public class Tests1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int number = sc.nextInt();
Tests1 obj1=new Tests1();
System.out.println(obj1.digit(number));
}
public boolean digit(int num) {
int count = 0;
while (num != 0) {
num = num / 10;
count++;
}
if (count == 1) {
return true;
}
return false;
}
}
My code check that the number is single digit or not. If it is a single digit number it return true else return false.

Related

How to ask for input until 2 integers are received?

I need to validate that user inputs two integers and as such, I need to continue asking him for input until he provides both inputs that are integers. Not sure how to implement it, but I came up with something like that but now struggling to implement the part that checks if coord1 and coord2 get correct types. If not, it of course gives me the NumberFormatException:
while (true) {
System.out.print("Enter the coordinates: ");
int coord1 = Integer.parseInt(scanner.next());
int coord2 = Integer.parseInt(scanner.next());
if (coord1 < 1 || coord1 > 3 || coord2 < 1 || coord2 > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
} else if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
continue;
}
break;
}
Can I solve it without using try / catch, since I haven't learned that yet, or is this the only way?
Thank you in advance and sorry, since I'm still learning Java syntax and ways of validation.
Instead of manually checking if the input is the right type, you could rely on the Scanner's methods hasNextInt() and nextInt().
The first one will check whether your input is an actual int and then you can proceed reading it with nextInt(). For further details about placing a nextLine() after reading a numeric type read the following question asked here on stack overflow.
Here I've also included your code in a sample main. I know yours was just a snippet with much more code around (I didn't have the cellOccupied method, for example) but I've just pasted it like so for a minimal testing. Besides, I've also parameterized your use case. It was a bit odd and redundant to repeat the same code for reading the user input applying the same coordinate-logic.
public class Main {
public static void main(String[] args) {
int coord1 = 0, coord2 = 0;
do {
coord1 = readCoordinate("Enter first coordinate: ");
coord2 = readCoordinate("Enter second coordinate: ");
//Showing an error message if the coords refer to an occupied cell
if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
}
} while (cellOccupied(field, coord1, coord2));
}
private static int readCoordinate(String message) {
int coord;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(message);
if (scanner.hasNextInt()) {
coord = scanner.nextInt();
//getting rid of the new line character after reading the int
scanner.nextLine();
//Checking coordinate value
if (coord < 1 || coord > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
}
} else {
//assigning an undesired value (since your coords must be between 1 and 3
coord = 0;
//getting rid of the wrong user input
scanner.nextLine();
//Showing an error message
System.out.println("Please enter an int value");
//Skipping directly to the loop's condition
continue;
}
break;
}
return coord;
}
}
On a side note, avoid declaring fields in a loop.
You can find here several suggestions. For example, you can use regular expressions. Create an isNumeric function that will tell you whether a given string is an integer:
public boolean isNumeric(String strNum) {
Pattern pattern = Pattern.compile("\\d+");
if (strNum == null) {
return false;
}
return pattern.matcher(strNum).matches();
}
And before pushing the scanner.next() to the integer parser, check it with the function.

Prompt user to enter values until the same value is entered thrice in a row

I have a question regarding loops. Basically the program rotates around prompting user to enter integers until three integers have been entered which are the same ones but the issue is if i enter a different integer at the beginning and then enter three same integer i am not able to make my program accept it as three similar integer in the row..
This is the actual question: Write a Java program that prompts the user to enter integers from the keyboard one at a time. The program stops reading integers once the user enters the same value three times consecutively (meaning three times in a row, one after the other). Once input is completed the program is to display the message “Same entered 3 in a row
output:
Enter an integer: 77
Enter an integer: 56
Enter an integer: 56
Enter an integer: 78
Enter an integer: 56
Enter an integer: 22
Enter an integer: 22
Enter an integer: 22
Same integer value entered thrice
I am not able to get the above output correctly. Can anyone please help me in this..
Here is the same program which i tried:
import java.util.Scanner;
public class Naim5c
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int count = 0;
int a,b,c;
do{
System.out.println("enter an integer");
a = input.nextInt();
System.out.println("enter an integer");
b = input.nextInt();
System.out.println("enter an integer");
c = input.nextInt();
if(a==b)
{
if(b==c)
{
System.out.println("Same integer entered thrice");
}
}
else if (b==c)
{
System.out.println("enter an integer");
a = input.nextInt();
if(c==a)
{
System.out.println("Same integer entered thrice");
}
}
//System.out.println("enter an integer");
//a = input.nextInt();
else if (c==a)
{
System.out.println("enter an integer");
b = input.nextInt();
if( a==b )
{
System.out.println("Same integer entered thrice");
}
}
}while(a!=b && b!=c);
}
}
By the look of it (at least according to you) you require the need to detect when a User enters three integer numbers of the same value three times in a row rather than throughout the entire entry cycle. All you really need is a counter variable and another integer variable to hold the previously entered value. Something like this:
Scanner input = new Scanner(System.in);
int a; // To hold User's current entry value.
int count = 0; // To hold the number of times the same value was entered.
int prevInt = 0; // To hold the value previously entered.
do{
// Since we're in a loop we only need to have
// a single prompt.
System.out.print("Enter an integer: --> ");
a = input.nextInt(); // Get User Input
// Is User entry equal to what what entered
// previously?
if (a == prevInt) {
// Yes it is...
count++; // Increment our counter
// if our counter reaches 3 then let's
// break out of our do/loop.
if (count == 3) { break; }
// Otherwise let's continue the loop from
// the start.
continue;
}
// Nope, not equal to the User's last entry so
// let's make prevInt hold the Users new entry.
prevInt = a;
// Let's reset our counter to 1. We need to set
// to 1 because the last User's input which is
// now held in prevInt is the actual first entry
// for the new integer value.
count = 1;
} while(count < 3); // Keep looping if our counter is less than 3
// Display that a triple entry was made.
System.out.println("Same integer (" + a + ") entered thrice");
You don't need three variables. Just one variable for remembering the last int and a counter variable for recording how many times you've seen the last integer.
int count = 0;
Integer prevInt = null;
do {
System.out.println("enter an integer");
int i = input.nextInt();
if (prevInt == null || i != prevInt) {
count = 1;
} else {
count++;
}
prevInt = i;
} while (count != 3);
System.out.println("Same integer value entered thrice");
You can try this.
Scanner input = new Scanner(System.in);
int num = 0; //holds the current input
boolean check = false; // checking for the input
ArrayList<Integer> number = new ArrayList<Integer>();
do {
System.out.println("Enter an integer");
num = input.nextInt();
number.add(num); // add the current input to the array list
if (number.size() >= 3) { // check if there's 3 or more values in the array
if (number.get(number.size() - 1) == number.get(number.size() - 2) && number.get(number.size() - 2) == number.get(number.size() - 3))
{ // check for input if the same
check = true;
System.out.println("\nSame integer value entered thrice");
}
}
} while(check == false);
// checking for loop to continue of no 3 consecutive input of number is the same
Hello if you want to make a loop you need the for command. And loops uses arrays
int[] I = new int[3]
for(j=0;j<3;j++)
{
System.out.println("enter an integer");
I[j] =input.nextInt();
}
if(I[0]==I[1] || I[1]==I[2]){
System.out.println("Same integer entered thrice");
continue;
}
Assume that code is inside your do while code. Feel free to reply if you have questions
You should simply loop everything back to inputing using "continue".

Using java scanner to check two conditions while taking user input

I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

How can I read a number in between 2 numbers?

I am fairly new to Java and I am trying to write a small program that asks a user to enter an integer between 0-4. I have written this so far and but it doesn't seem to work! Can anyone tell me where am I wrong?
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
{
System.out.print("choose a player: ");
myChar = in.nextInt();
}while(myChar>0 && myChar<4);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Now I want the number to be 1,2 or 3 or else it loop until the user input one of these but the program accept any number at the moment. Where am I wrong?
You are missing a do keyword in your loop. Also your conditional should be reversed:
public static void main(String[] argh) {
int myChar;
Scanner in = new Scanner(System.in);
do {
System.out.print("choose a player: ");
myChar = in.nextInt();
} while (myChar <= 0 || myChar >= 4);
System.out.println("--------");
System.out.println("you chose " + myChar);
}
Your while condition is wrong.
You are checking if the char is larger than 0 AND lower than 4, and if it is, it will do the loop again, while what you are after is the oposite.
Change the statement to check if myChar is smaller than 1 OR higher than 3.
myChar < 1 || myChar > 3
You are also missing a do at the beginning of the do-while.
You haf two problems in your code:
You are putting the while in a wrong way, you should put a do-while statement or put the while before the {...}.
You also want to run the loop when you put a wrong number (<1 or >3), not when you put the correct number(between 1 and 3)... So you also need to change the expression.
My code would be something like this:
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
do{
System.out.print("choose a player: ");
myChar = in.nextInt();
} while(myChar<1 || myChar>3);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Your loop should look like
while (true) {
System.out.print("Choose a player: ");
myChar = in.nextInt();
if (myChar > 0 && myChar < 4) {
break; // out of the loop
}
}
That is you only break; out of it if the scanned value is either 1, 2, or 3.
#Ali, while(true) approach is perfectly fine. In fact, it's far more common to see them than a do-while() in actual code running out there. The downvote received is subjective and based on individual coding style preference rather than an indication on the correctness of the answer.

Categories

Resources