This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I've been debugging the following program from hours yet I cannot find why is the sanner not taking the input for the field name
This is my source code:
import java.util.Scanner;
public class Student
{
int rollNo;
String name;
double percentageMarks;
static Scanner input = new Scanner(System.in);
public void accept()
{
System.out.print("Enter roll no: ");
rollNo = input.nextInt();
System.out.print("Enter Name: ");
name = input.nextLine();
System.out.print("Enter percentageMarks: ");
percentageMarks = input.nextDouble();
}
public void display()
{
System.out.println("Name: " +name);
System.out.println("roll no: " +rollNo);
System.out.println("Percentage marks: " +percentageMarks);
}
public static void main(String[] args)
{
Student s1 = new Student(), s2 = new Student();
s1.accept();
s2.accept();
if(s1.percentageMarks>s2.percentageMarks)
s1.display();
else if (s2.percentageMarks>s1.percentageMarks)
s2.display();
else
System.out.println("Both students has same marks");
}
}
This is an output sample:
Enter roll no: 1
Enter Name: Enter percentageMarks:
As seen, without it allowing to enter student name, its prompting to enter student percentage marks.
Any suggestion please?
This is because you first have the input.nextInt() and after it is finished it is not going to the next line. Just parse the whole first line as Integer.parseInt(scanner.nextLine()) and you will get your input for the name after that.
Related
I am writing a small program to create a password based off what the user inputs their first middle last name and the birthday and create a password off that and i don't know what i am doing but believe i need multiple scanners but when i do i get this error "variable scan is already defined in method main(string[]) Scanner scan = new Scanner(System.in);"
here is my code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("Please Enter your first name: ");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
System.out.print("Please Enter your last name: ");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
scan.close();
}
}
anythoughs on what could work?
You do not need multiple Scanner objects to accept multiple inputs. You should create one Scanner object and use it to collect as many inputs as you want.
Here is an example:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your first name: ");
String fname = input.nextLine();
System.out.println("Enter your last name: ");
String lname = input.nextLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(input.nextLine());
System.out.println("Your details as entered:");
System.out.println("First Name: " + fname);
System.out.println("Last Name: " + lname);
System.out.println("Age: " + age);
}
}
Also some extra resources for you (for Scanner class): https://www.w3schools.com/java/java_user_input.asp
Edit:
replaced next() with nextLine()
replaced nextInt() with Integer.parseInt(input.nextLine());
Thank you very much for the information #Arvind Kumar Avinash. Reference thread: Scanner is skipping nextLine() after using next() or nextFoo()?.
That is because you cannot have two variables with the same name within the same scope.
You should rename one of them ..
Note that you did the same with the String variable name ;)
If you want to keep the same name for both use, then you should not re-declare the variable(s):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan;
String name;
System.out.print("Please Enter your first name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
scan.close();
System.out.print("Please Enter your last name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
scan.close();
}
}
Notes:
in this example, you will loosen the first value entered by the user. You might want to use an other variable name to store the last name.
there is obviously no reason to instantiate two different Scanner objects with the same InputStream.
Is the second part a good practice in order to avoid user input mismatch?
public class StringsAsPrimitiveDate{
Scanner input= new Scanner(System.in);
System.out.println("Please enter your number:");
int numberOne=input.nextInt();
}
Or
public class StringsAsPrimitiveDate{
Scanner input= new Scanner(System.in);
System.out.println("Please enter your number:");
String numberOne=input.next();
int result = Integer.parseInt(numberOne);
}
Thank you
A common problem with nextInt is that it leaves behind a new line character which may be accidentally automatically consumed by the next scan. Consider the following code:
import java.util.Scanner;
class Main{
public static void main(String args[]) {
int rollNo;
String name;
Scanner scan=new Scanner(System.in);
while (true) {
System.out.print("Enter the roll no of the student: ");
rollNo=scan.nextInt();
System.out.print("Enter the name of the student: ");
name=scan.nextLine();
System.out.printf("Roll no. %d, Name: %s has been registered%n",rollNo, name);
}
}
}
A sample run:
Enter the roll no of the student: 1
Enter the name of the student: Roll no. 1, Name: has been registered
Enter the roll no of the student: Arvind
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:10)
Note that this problem can occur even with next but not with nextLine as shown with the following code:
import java.util.Scanner;
class Main {
public static void main(String args[]) {
int rollNo = 0;
String name;
boolean valid = true;
Scanner scan = new Scanner(System.in);
while (true) {
do {
System.out.print("Enter the roll no of the student: ");
try {
rollNo = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("The value should be an integer.");
valid = false;
}
} while (!valid);
System.out.print("Enter the name of the student: ");
name = scan.nextLine();
System.out.println("Roll no. " + rollNo + ", Name: " + name + " has been registered");
}
}
}
A sample run:
Enter the roll no of the student: 1
Enter the name of the student: Arvind
Roll no. 1, Name: Arvind has been registered
Enter the roll no of the student: a
The value should be an integer.
Enter the roll no of the student: 12.5
The value should be an integer.
Enter the roll no of the student: 2
Enter the roll no of the student: Avinash
The value should be an integer.
Enter the roll no of the student:
Conclusion: it is better to use nextLine with proper logic (e.g. exception handling, loop back on invalid input etc.) instead of next or nextInt to avoid issues mentioned above. I also recommend you go through documentation on Scanner.
It's not letting me put my name in but it does the age works fine.
I know i can change the order of the statements but is there another way I could do it?
import java.util.Scanner;
public class ScannerErr2
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner(System.in);
String name;
int age;
System.out.print("Enter your age : ");
age= keyboard.nextInt();
System.out.print("Enter your name: ");
name= keyboard.nextLine();
System.out.println("Age : "+age);
System.out.println("Name: "+name);
}
}
You problem is that the next int doesn't consider the new line character which goes in the input for your name part. Hence name is returned as blank.
You can change your code in 2 ways:
System.out.print("Enter your age : ");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.print("Enter your name: ");
name = keyboard.nextLine();
or
System.out.print("Enter your age : ");
age = Integer.parseInt(keyboard.nextLine().trim());
System.out.print("Enter your name: ");
name = keyboard.nextLine();
I personally like the second way.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
OK, So I have this code:
import java.util.Scanner;
public class Library
{
int Acc_Num;
String Title;
String Author;
public void input()
{
Scanner s = new Scanner (System.in);
System.out.println("Enter Your Accession Number");
Acc_Num = s.nextInt();
System.out.println("Enter The Title Of The Book");
Title = s.nextLine();
System.out.println("Enter The Author Of The Book");
Author = s.next();
}
public void compute()
{
Scanner s = new Scanner (System.in);
System.out.println("Enter Number Of Days Late");
int Day_Late = s.nextInt();
int Fine = 2 * Day_Late;
System.out.println("Fine: " + Fine);
}
public void display()
{
System.out.println("Accession Number\t\tTitle\t\tAuthor");
System.out.println(Acc_Num + "\t\t" + Title + "\t\t" + Author);
}
public static void main(String[] args)
{
Library Mem1 = new Library();
Mem1.input();
Mem1.compute();
Mem1.display();
}
}
The thing is, when it goes into the function to get input, it take input for Title but not for author. Have attached a screenshot of the program running in cmd.
Would love to have this solved.
Is this a Scanner glitch? Or Am I doing something wrong?
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
The below given program is for reading inputs using scanner. The problem i am facing here is if i try to give an integer value first then it wont allow me to give string value next. it skips automatically to the next line. Any help will be appreciated
import java.io.*;
import java.util.Scanner;
class Employee
{
int empid,salary;
String empname,designation;
public static void main(String args[])
{
Employee bha=new Employee();
bha.details();
bha.display();
}
void details()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the empid");
empid=s.nextInt();//i'm am able to give the value here
System.out.println("enter the employee name");
empname=s.nextLine();// automatically skips to the next line(unable to give value)
System.out.println("enter the employee designation");
designation=s.nextLine();
System.out.println("enter the employee salary");
salary=s.nextInt();
}
void display()
{
System.out.println("the employee id is"+empid);
System.out.println("the employee name is"+empname);
System.out.println("the employee designation
is"+designation);
System.out.println("the employee salary is"+salary);
}
}
Try this way:
System.out.println("enter the empid");
Scanner s = new Scanner(System.in);
empid = Integer.parseInt(s.next());
System.out.println("enter the employee name");
empname = s.next();
System.out.println("enter the employee designation");
designation = s.next();
System.out.println("enter the employee salary");
salary = Integer.parseInt(s.next());