how to have multiple scanners for multiple user inputs - java

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.

Related

How do I accept the user input and put it into the while condition

This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}

Is it safe and a better practice to accept Strings instead of integers or doubles?

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.

Scanner skipping inputs? [duplicate]

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.

Trouble using nextInt and nextLine()

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.

How to execute Print statement after getting input from user

I have code which is:
import java.util.Scanner;
class shoham
{
public static void main (String args[])
{
System.out.println("Enter your name: ");
Scanner name = new Scanner(System.in);
System.out.println("Your name is: ");
System.out.print(name.nextLine());
}
}
When I execute this command, I get output like:
Enter your name:
Your name is:
***** (user input)
***** (output)
Can anyone give a code that gives output like:
Enter your name: **** - (user input)
Your name is: **** - (output from user input)`
Well you're reading input after your print statements. You probably want:
Scanner in = new Scanner(System.in); // do this first, and give it a
// better name
System.out.print("Enter your name: "); // use print to keep it on one line
String name = in.nextLine(); // read input, store it
System.out.print("Your name is: ");
System.out.println(name); // print name
Enter your name: Joe
Your name is: Joe
You may try something like this ie try using print only instead of println:-
Scanner name = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = name.nextLine();
System.out.print("Your name is: ");
System.out.println(name);
try this
public static void main (String args[])
{
System.out.print("Enter your name: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine()
System.out.println("Your name is: "+name);
}
here is your code:
System.out.println("Enter your name: ");
Scanner name = new Scanner(System.in);
System.out.println("Your name is: "+name.nextLine());
You have got lot of sloutions here, but you need to know the issue with your code is,
You did not store the input from the user.
System.out.print("Enter your name: ");
String name = name.nextLine(); // read input, store it

Categories