Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).
Related
why do I need to input 2 times? please help I'm new to java, can't find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed the do while but it still asks for the second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
I have updated your code. This will work for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output :
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Explanation : If you are giving valid data, then the loop will continue to take inputs (not taking inputs twice). As soon as, you give invalid data, then, the code will prompt you to enter the valid data and loop will stop executing as you made valid = false.
The reason why it asks you for input twice is due to you in.hasNextInt() which will check your scanner for input from the system. Since your system does not have any input due to you calling age = in.nextInt(); which will move the scanner to the next word before your in.hasNextInt(), The function in.hasNextInt() will require you to input something so that it can validate if it is an Int or not.
what we want to do, is to first check the current scanner's input if it has an integer before we either store it inside age or loop again and ask for new input.
A better way of checking would be to do something like this.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = 0;
System.out.println("Enter your age: ");
while(!in.hasNextInt()){// checks if scanner's next input is an int, return true if next input is not an Int and the while loop continues till the next input is an Int
System.out.println("Please enter a valid age: ");
in.nextLine();//move the scanner to receive the next nextLine
//this is important so the hasNextInt() wont keep checking the same thing
}
//it will only exit the while loop when user have successfully enter an interger for the first word they inputted.
age = in.nextInt();
System.out.println("Your age is: " + age);
}
}
Output:
Enter your age:
boy
Please enter a valid age:
boy girl
Please enter a valid age:
5
Your age is: 5
Hi : D there is becuase of the !in.hasNextInt() it will cause you need to do the input again but you can change it to other condition like if the age is bigger than certain value.
public class stackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age =0 ;
boolean valid = false;
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(age>90) {
System.out.println("Please enter a valid age");
valid=true;
}
else valid=false;
}while(valid);
System.out.println("Age: " + age);
}
}
You should move the System.out.println("Enter your age: "); statement outside the do-while loop.
I have a method that must get an integer as input. How can I check that it is a integer certainly. if input is a string so get number again.
public int getMobileNumber() {
System.out.println("Enter Mobile Number: ");
int mobileNumber = input.nextLong();
System.out.println("Mobile Number Registered!");
return mobileNumber;
}
You can use the hasNextInt method and a while loop to get definitely an integer:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!sc.hasNextInt()) {
System.out.printf("Your input was \"%s\". Please enter a number:%n", sc.next());
}
int num = sc.nextInt();
System.out.println(num);
sc.close();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String sent = "y";
int a = 0;
int b = 0;
System.out.println("Welcome!\nThis program compares two letters in a sentence.");
while(!sent.equalsIgnoreCase("X")) {
System.out.print("Enter a sentence or X to exit: ");
sent = input.next();
System.out.print("Enter the numeric location of the first letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the first letter: ");
}
a = input.nextInt();
System.out.print("Enter the numeric location of the second letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the second letter: ");
}
b = input.nextInt();
System.out.println();
char c = sent.charAt(a);
char d = sent.charAt(b);
if(c==d) {
System.out.println(c+" and "+d+" are identical.\n");
}
else {
System.out.println(c+ " and "+ d + " are unique characters. \n");
}
}
System.out.print("GoodBye!");
}
This loop continues to run even if you input X and I don't know why. Also, when you input a text instead of a number, the error message will like so:
Error! Please enter a number not text!
Enter the numeric location of the first letter: Error! Please enter a number not text!
Enter the numeric location of the first letter:
Only the third sentence will take in user input.
This code sent = input.next()
is not reading a whole sentence. It just reads one word.
Try nextLine() instead.
Also, you should test the exit condition immediately after sent is set.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String sent = "y";
int a = 0;
int b = 0;
System.out.println("Welcome!\nThis program compares two letters in a sentence.");
System.out.print("Enter a sentence or X to exit: ");
sent = input.next();
while(!sent.equalsIgnoreCase("X")) {
//moved accepting input above while condition.This will fix
//X not recognized issue
System.out.print("Enter the numeric location of the first letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the first letter: ");
}
a = input.nextInt();
System.out.print("Enter the numeric location of the second letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the second letter: ");
}
b = input.nextInt();
System.out.println();
char c = sent.charAt(a);
char d = sent.charAt(b);
if(c==d) {
System.out.println(c+" and "+d+" are identical.\n");
}
else {
System.out.println(c+ " and "+ d + " are unique characters. \n");
}
}
System.out.print("GoodBye!");
}
I am going to post my code right away and ask the question below it.
System.out.println("Enter your starting integer: ");
firstInt = scnr.nextInt();
System.out.println("Enter your last integer: ");
secondInt = scnr.nextInt();
int i = firstInt;
while (i < secondInt) {
The first input is taken just fine. But when I try to input to secondInt, I hit enter and it wont move onto my while loop it is just stuck in the scanner. I hit enter and i just move down a line to input more. I watn it to move to my while loop. This is probably an easy fix but im pretty new to coding so any help would be appreciated. Thanks in advance!
import java.util.Scanner;
public class Tyler
{
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
// input first int
System.out.print("Enter your starting integer: ");
int firstInt = stdin.nextInt();
//input second int
// consume line
stdin.nextLine();
System.out.print("Enter your last integer: ");
int secondInt = stdin.nextInt();
// output data
// There was no way to break out of your while loop so this should be done with an If/else
if (firstInt <= secondInt)
{
System.out.println("First number is less then second number");
}
else
{
System.out.println("Second number is less then first number");
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
String userIn= in.next();
if(userIn.equals("e")){
System.out.println("Please enter your text that you want to encrypt: ");
String userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
int userS = in.nextInt();
if(userS < 0 || userS > 25){
System.out.print("Invalid shift key, please enter a valid shift key: ");
userS = in.nextInt();
}
In my above program at following part of code:
System.out.println("Please enter your text that you want to encrypt: ");
String userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
It is skipping this userInput, it goes over it and asks for the shift key before I enter the text.
This fixed it (tested in Eclipse):
Scanner in = new Scanner(System.in);
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
String userInput = in.nextLine();
if (userInput.equals("e"))
{
System.out.println("Please enter your text that you want to encrypt: ");
userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
int userS = Integer.parseInt(in.nextLine());
if (userS < 0 || userS > 25)
{
System.out.print("Invalid shift key, please enter a valid shift key: ");
userS = Integer.parseInt(in.nextLine());
}
}
in.close();
I changed your userIn variable to just be userInput, since we didn't need it; your next() call was also changed to nextLine().
I also changed all your nextInt()'s to nextLine()'s. This will help you avoid an Exception later on.
Lastly, always close a Scanner when you are done with it to conserve system resources.
Change:
String userInput = in.nextLine()
to
in.nextLine(); String userInput = in.nextLine();
Simple, change you code to
String userInput = in.next();