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 ?
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
The questions are in the comments of the code, sorry for that, I thought it's neater, as the flow is important, I guess...
import java.util.Scanner;
public class ReadingUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");
int number = 0;
int total = 0;
int counter = 0;
while (counter < 10) {
System.out.println("Enter number #" + (counter + 1));
boolean hasNextInt = scanner.hasNextInt(); // here we open the prompt for user to enter the value/s*
// internally, we are ready to check if the input is going to be int
// user types the value/s and clicks enter
// let's presume, he/she typed '3'
// internally, user's input is like that (if Windows**) - '3\n'
// because when user presses Enter - \n is added to what he/she typed
if (hasNextInt) { // the app checks, ant it's int, that is, it's OK (true)
number = scanner.nextInt(); //here the application grabs user's input
//but, internally, it grabs only '3', because 'nextInt()' grabs only ints
// and doesn't "care" about the new feed/line - \n - character
// so, '\n' is left in Scanner's buffer!
counter++;
total += number;
} else {
System.out.println("Invalid Input! Try again!");
}
//scanner.nextLine(); // let's presume, this commented line, on the left of this line of comment, is absent in our code
// the flow of our code goes to boolean hasNextInt = scanner.hasNextInt();
// and again internally, we are ready to check if the input is going to be int
// and again the user is prompted (by a blinking cursor) to type his/her input
// and at this moment user types either a numeric again or a non-numeric character (a letter/letters)
// let's presume he/she is typing '4'
// and again, internally, user's input is actually like that (if Windows**) - '4\n'
// but scanner.hasNextInt() says 'OK', for the int is there! and it doesn't care about '\n'
//
// Now, let's presume that user (this time or next time) types 'a'
// Do we actually have 'a\n' ???
// and this time scanner.hasNextInt() says 'Alarm' - 'false'
// thus the input doesn't go to number = scanner.nextInt();
// So, does it mean that 'a\n' (or 'a') remains in Scanner's buffer???
// and it (scanner.hasNextInt()) kicks us to 'else'
// and we have an endless loop:
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Why?
// Is there still 'a' (or 'a\n') and scanner.hasNextInt() throws the flow to 'else' endlessly,
// because "The scanner does not advance past any input"* ???
//
// or: there's only '\n', and again its not int, and we result in endless loop ???
// And finally, is that a different case? https://www.youtube.com/watch?v=_xqzmDyLWvs
// And PS: Is there anything wrong in my description in the comments?
// So what do we 'consume' by scanner.nextLine(); ???
}
scanner.close();
System.out.println("Thank you, your total is " + total);
}
}
// *This is from Oracle :(https://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29)
"hasNextInt
public boolean hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
// **https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019KZDSA2
Create another scanner object instead and forget about what is left in the internal buffer.
public class ReadingUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");
int number = 0;
int total = 0;
int counter = 0;
while (counter < 10) {
System.out.println("Enter number #" + (counter + 1));
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
number = scanner.nextInt();
counter++;
total += number;
} else {
System.out.println("Invalid Input! Try again!");
scanner = new Scanner(System.in);
}
}
scanner.close();
System.out.println("Thank you, your total is " + total);
}
}
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".
I am attempting to make sure the user input int type only and make sure the integer inputted is greater than 0.
I was able to come up with the following to make sure the input is int type:
Scanner scan = new Scanner(System.in);
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
But how should I include a condition checking to make sure the integer is greater than 0 as well?
The problem with your current approach is you've already ready the value from the Scanner before it reaches int input = scan.nextInt();, meaning that by the time you use nextInt, there's nothing in the Scanner to be read and it will wait for the next input from user...
Instead, you could read the String from the Scanner using next, use Integer.parseInt to try and parse the result to an int and then check the result, for example...
Scanner scanner = new Scanner(System.in);
int intValue = -1;
do {
System.out.print("Please enter a integer value greater than 0: ");
String next = scanner.next();
try {
intValue = Integer.parseInt(next);
} catch (NumberFormatException exp) {
}
} while (intValue < 0);
System.out.println("You input " + intValue);
put an if statement inside your while loop like this
if(num <= 0){
System.out.println("Enter a number greater than zero");
}
else{
break;
}
You may use a condition in your code but not in the loop as.
`
Scanner scan = new Scanner(System.in);
abc:
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
if(input <= 0){
goto abc;
}
`
using .isDigit() method then checking to see if that number is greater than 0 if it is a digit
import java.util.*;
public class ConvertBinaryToInteger{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
final String EXIT="exit";
System.out.println("This program will convert a binary into an integer.");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
String word=scan.nextLine();
while(!word.equals(EXIT)){
while(!word.equals(EXIT)){
boolean valid = false;
while (!valid) {
System.out.println("Enter a binary number: ");
String binary = scan.next();
boolean isBinary = true;//first convert the 'binary' string into a char array and check for each char whether it is zero or one
char[] bits = binary.toCharArray();
for(int j=0; j<bits.length; j++){//read the inputs
if( (bits[j] != '0') && (bits[j] != '1') ){//check the inputs
isBinary = false;
break;
}
}
if(!isBinary){//not binary
System.out.println("This is not a binary number.");
System.out.println("Please enter a number that contains only 1's and 0's.");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
word=scan.nextLine();
}
else{//binary
int integer = 0;
int temp;
int i = 0;
temp = Integer.parseInt(binary);
while (temp != 0){
int r = temp % 10;
double value = r * Math.pow(2, i);
i++;
integer = (int) (integer + value);
temp /= 10;
}
System.out.println("Integer of " + binary + " is " + integer+".");
System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
word=scan.nextLine();
}
System.out.println();
scan = new Scanner(System.in);
}
}
}System.out.println("Program ended.");
}
}
cannot exit after entered a correct binary. Please help me to change the program...
if you didn't exit in the first place, you cannot end the program..
while (!valid) {
valid is never updated. If they want to exit, set valid to true as well as updating the value of word.
As pointed out by #AnthonyGrist, removing the while(!valid) loop altogether will also fix this issue.
Check this code
it is up and running
PS: removing the !valid condition will also not lead to termination of the program on entering exit. i tried it.
The issue is you are displaying the message and also writing scan.nextline() immediately, which accepts a blank, this is neither = to exit and also valid whether set to true or not, will always be initialized to false, as it enters the word.equals(.. condition.