public class MetricConversion {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String masses = "null";
String volumes = "null";
String temps = "null";
String lengths = "null";
int answer1 = 0;
String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"};
System.out.println("What would you like to convert?");
for(int i = 0;i<options.length;i++)
System.out.println(options[i]);
while(!input.hasNextInt() || input.nextInt() > options.length)
{
String garbage = input.nextLine();
System.out.println("That input is not valid, try again");
}
answer1 = input.nextInt();
input.nextLine();
The problem I am having is that the
while(!input.hasNextInt() || input.nextInt() > options.length)
is taking 2 valid inputs instead of 1 in order to make
answer1 = input.nextInt();
For example, when entering an invalid input it correctly prints my error message, but when entering a valid input I have to enter it twice in order to break the loop. However if I use the while loop without the || it only takes one value like it's supposed to.
You're consuming the value without assigning it to a variable. You can assign it within the loop condition like this:
while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)
You are consuming scanner argument in while loop:
while(!input.hasNextInt()){
int argument = input.nextInt();
if(argument > options.length){
System.out.println("That input is not valid, try again");
continue; // get back to the start
}
// correctly handle your argument
}
Related
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 ?
Is there any way to implement Scanner.hasNextInt() so that it can check not only the i+1 token but the i+2 token? I am looking for a way to check if both inputs are numbers without printing the same error message twice.
Input should be in the form
1 2
and I am trying to alert the user if input is of the form
1 a, a 1, a a, aa aa, 1a 1, etc...
What I wish it would look like: (does not work this way)
int pile1, pile2;
// the second call to reader.hasNextInt() would be verifying pile2 to be int
if (reader.hasNextInt() && reader.hasNextInt())
{
pile1 = reader.nextInt();
pile2 = reader.nextInt();
}
else
{
System.out.println("Your input is malformed. Try again");
}
What I currently have:
int pile1, pile2;
if (reader.hasNextInt())
pile1 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
if (reader.hasNextInt())
pile2 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
You can use
hasNext(String pattern) this method returns true if the next token matches the pattern constructed from the specified string.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
List<Integer> data = new ArrayList<Integer>();
System.out.println("input count of numbers to inputed:\t");
int limit = 0;
if (reader.hasNext("\\d+")) {
reader.nextInt();
} else {
System.out.println("wrong input");
return;
}
System.out.println("please input data:\t");
for (int i = 0; i < limit; i++) {
if (reader.hasNext("\\d+")) {
data.add(reader.nextInt());
} else {
System.out.println("Your input is malformed. Try again");
break;
}
}
reader.close();
}
assumption:Since you need to stop scanning ,one must have predefined limit set or special exit condition from loop.
Here's the program that I'm working on but I'm having problems with figuring out how to ask the user if they are done with it by saying a word or number.
import java.util.Scanner;
class paliindrome {
public static void main(String args[]) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
System.out.println(" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + isPalindrome.charAt(i);
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
char answer;
do {
aGame.play ();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
} while (answer == 'y' || answer == 'Y');
}
}
Put your entire application within the loop. One easy way would be to default answer to y (and you can use Character.toUpperCase(char) to eliminate the or) and something like
PalindromeChecker aGame = new PalindromeChecker();
char answer = 'y';
while (Character.toUpperCase(answer) == 'Y') {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// ... The rest of your code ...
aGame.play();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
}
There is one more way to solve your problem:
Put your entire code in a infinite while loop like this while(true), on the last line of loop just before exiting from the loop, u can ask user if he/she wants to continue. If answer is yes, then use the code System.exit(0) to exit from the program or if you want to just break from the loop use break; in the if condition.
You can use below code to ask user for quit.
boolean quit = false;
Scanner scanner = null;
try {
do {
System.out.println("Do you want to quit? (true/false)\n");
scanner = new Scanner(System.in);
String input = scanner.nextLine();
quit = Boolean.parseBoolean(input);
} while (!quit);
} finally {
scanner.close();
}
import java.util.Scanner;
public class paliindrome {
public static void main(String[] args) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
for (;;) {// or while(true)
System.out.println(
" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + isPalindrome.charAt(i);
}
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
System.out.print("\n Do you want to continue (y or n)?");
char answer = keyboard.next().charAt(0);
if (answer != 'y' && answer != 'Y') {
break;
}else{
aGame.play ();
}
}
}
}
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
Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful