I am very new to Java and I am having some issues making my code do what I want it to.
So this is my code:
System.out.println("Please enter an integer: ");
int another_int_value = Integer.parseInt(input.nextLine());
This outputs the message Please enter an integer: and then a blank line where the user can type an integer let's say the user inputs the integer 3.
The following line starts right after the 3, but I want it to skip one, how do I make this happen?
I tried adding the line input.nextLine() but then the user has to press ENTER, twice and I don't want that. Any suggestions?
Alternatively you could have it to where the user inputs code after the semicolon by removing the .println and just using .print. No extra code needed after.
System.out.print("Please enter an integer: ");
int another_int_value = Integer.parseInt(input.nextLine());
This should work
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
System.out.println();
int another_int_value = Integer.parseInt(input.nextLine());
System.out.println();
}
}
Related
Ive written a small Java code to calculate the product of two integers input by the user using Scanner. The user is forced to input integer values. The code is shown below.
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int x=0,y=0;
Scanner sc=new Scanner(System.in);
//Asks for the first number until the user inputs an integer
System.out.println("First number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. First number:");
sc.nextLine();
}
x=sc.nextInt();
//Asks for the second number until the user inputs an integer
System.out.println("Second number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. Second number:");
sc.nextLine();
}
y=sc.nextInt();
//Show result
System.out.println(x+"*"+y+"="+x*y);
}
}
The loop for the first number works fine. But, the second doesn't: if the user inputs something that is not an integer value, the message "Not valid. Second number:" is shown twice!
First number:
g
Not valid. First number:
2
Second number:
f
Not valid. Second number:
Not valid. Second number:
4
2*4=8
What is the reason for this behaviour? I guess I'm doing something wrong.
I've tried to use two different Scanners (one for each number) and the problem dissapears, but I don't think that creating lots of instances is the correct path.
Can anybody help?
Thanks.
Because even after accepting the first int value there is still the newline character to consume,
so change to
x=sc.nextInt();
sc.nextLine();
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
I use the while loop to check if the input is an integer or not, the first time encounter a wrong type, it works fine, execute the statements in the loop once. But from the second time, it runs the statements in the loop twice. I already use sc.nextLine() to clear the previous input, still....
Pls ignore it is a date that i need to get in this case, I understand there are other methods to get a date, assume it is an integer the program need later.
What I want to know is what is causing the loop to run twice from the second time before taking a new input? And how to avoid this?
Thanks
I can copy the whole program if needed, but it seems a bit long...
It is the getInput() method with the problem:
import java.util.Scanner;
public class DayOfWeek {
static Scanner sc = new Scanner(System.in);
static int day, month, year;
public static void main(String[] args) {
System.out.println("");
System.out.print("Please enter the DAY in numeric form: ");
day = getInput();
System.out.print("Please enter the MONTH in numeric form: ");
month = getInput();
System.out.print("Please enter the YEAR in numeric form: ");
year = getInput();
}
public static int getInput() {
while (!sc.hasNextInt()) {
sc.nextLine();
System.out.print("Please enter integer only. Try again: ");
}
return sc.nextInt();
}
}
this is the result on the console :
Please enter the DAY in numeric form: a
Please enter integer only. Try again: 1
Please enter the MONTH in numeric form: b
Please enter integer only. Try again: Please enter integer only. Try again: 1
Please enter the YEAR in numeric form: c
Please enter integer only. Try again: Please enter integer only. Try again:
Because after it reads the integer value, it will leave the [ENTER] from System.in. And when you start the next getInput(), [ENTER] is tested by sc.hasNextInt() and return false. So it will loop twice for the second and third round of input.
Try modify your method as below. It will discard anything user input after the 1st integer for each round of input.
public static int getInput() {
while (!sc.hasNextInt())
{
sc.nextLine();
System.out.print("Please enter integer only. Try again: ");
}
int result = sc.nextInt();
sc.nextLine();
return result;
}
I am new to java and doing an assignment.
I have to request 3 inputs from the user and I have validation.
If I do it with only one instance of the scanner I get all messed up.
If I use three instances with a bit of workaround my code works.
Only I guess this is not best practice.
I have been reading a bit the manual regarding the scanner, but cannot understand the problem
Thanks
enter code here
Scanner input=new Scanner(System.in);
Scanner input2=new Scanner(System.in);
int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;
System.out.print("\n Please enter a number: ");
while(!input.hasNextInt()){
System.out.println("***** Error: the char inserted is not a number! *****");
String input_wrong=input.next();
System.out.print("\n Please enter a number: ");
}
input_integer=input.nextInt();
System.out.print("\n Please enter a double: ");
while(!input.hasNextDouble()){
System.out.println("***** Error: the char inserted is not a double! *****");
String input_wrong=input.next();
System.out.print("\n Please enter an double: ");
}
input_double=input.nextDouble();
System.out.print("\nPlease enter a string: ");
input_string=input.nextLine();
So I had two create 3 scanner instances and also to use a string to assign the wrong input in the while cycle to the able to prompt again.
Any suggestion?
I am sure there is a better way but I would try to understand..
Thanks!
I'm not exactly sure I understand what problem you're having, but scanner has some strange behaviors which are not immediately obvious. For instance, if you type "1234bubble" then press enter, then nextInt() will return 1234 and the next nextLine() will say "bubble". That is usually not desired behavior for inputs like this because "1234bubble" is not an integer and should have failed when the user pressed enter.
For that reason, I typically only use the function nextLine(). Then, I just process the data manually using functions like Integer.parseInt(..). That way, I can guarantee that I'm processing the whole line in a clear and obvious manner, unlike other techniques which create confusing code.
Here's how I would have written your program:
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main
{
static Random rand = new Random();
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
int input_integer = 0;
double input_double = 0.0;
String input_string = "";
double value = 0;
while (true)
{
System.out.print("Please enter an integer: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into an integer
input_integer = Integer.parseInt(text);
// Turning it into an int succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an int failed.
System.out.println("***** Error: the text inserted is not an integer! *****");
}
}
while (true)
{
System.out.print("Please enter a double: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into a double
input_double = Double.parseDouble(text);
// Turning it into an double succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an double failed.
System.out.println("***** Error: the text inserted is not a double! *****");
}
}
System.out.print("Please enter a string: ");
input_string = input.nextLine();
// This is done automatically when the program stops, but it's
// a good habit to get into for longer running programs.
input.close();
}
}
I am having trouble reading in strings from the user after reading in an int. Essentially I have to get an int from the user and then several strings. I can successfully get the user's int. However, when I begin asking for strings (author, subject, etc...), my scanner "skips" over the first string input.
For example, my output looks like this:
Enter your choice:
2
Enter author:
Enter subject:
subject
As you can see, the user is never able to enter the author, and my scanner stores null into the author string.
Here is the code that produces the above output:
String author;
String subject;
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter choice:");
choice = input.nextInt();
System.out.println("Enter author:");
author = input.nextLine();
System.out.println("Enter subject:");
subject = input.nextLine();
Any help would be greatly appreciated. Thank you!
-Preston Donovan
The problem is that when you use readLine it reads from the last read token to the end of the current line containing that token. It does not automatically move to the next line and then read the entire line.
Either use readLine consistently and parse the strings to integers where appropriate, or add an extra call to readLine:
System.out.println("Enter choice:");
choice = input.nextInt();
input.nextLine(); // Discard the rest of the line.
System.out.println("Enter author:");
author = input.nextLine();
This works perfectly.
Although while making previous programs like the one below it was not required. Can anyone explain this?
import java.util.Scanner;
public class Average Marks {
public static void main(String[] args) {
Scanner s = new Scanner ( System.in);
System.out.print("Enter your name: ");
String name=s.next();
System.out.print("Enter marks in three subjects: ");
int marks1=s.nextInt();
int marks2=s.nextInt();
int marks3=s.nextInt();
double average = ( marks1+marks2+marks3)/3.0;
System.out.println("\nName: "+name);
System.out.println("Average: "+average);