This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
System.out.println();
}
The code will only allow me to input a full name once, ie John Doe. It will not let me enter it with other doubles in the array. Why is this?
I got your error. When you enter double, you press enter. That is a new line which was taken instead of another name. Then it is expecting double but you are entering another name. So you get an input Mismatch.
After input.nextDouble() write input.nextLine();
The code should look like this.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[]repName = new String[5];
double[]salesAmount = new double[5];
System.out.println("Please Enter Sales Reps Name Followed By Monthly Sales: \n");
for (int i = 0 ; i < repName.length; i++ )
{
System.out.print("Sales Rep (Full Name): " );
repName[i] = input.nextLine();
System.out.print("Monthly Sales: € " );
salesAmount[i] = input.nextDouble();
input.nextLine();
System.out.println();
}
}
I have run your code, It's running well I think while entering salary you have not hit Enter key of your keybord.
I found that you are using loop over the length of person name. I think it is something wrong.
An easy way to solve this is to just use the next method instead of nextLine.
repName[i] = input.next();
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I want to make a program that will read user inputs and will printout them gradually. But when I am running the code, in the Console area, the first line is automatically skipping. But when I am taking input as Integer, all is running well. Where is my fault?
import java.util.*;
public class MainClass {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int limit, i, j;
System.out.print("How many names you want to take: ");
limit = input.nextInt();
String[] name = new String[limit];
for (i = 0; i < name.length; i++) {
System.out.print("Enter your name: ");
name[i] = input.nextLine();
}
for (String output : name) {
System.out.println("Names are: " + output);
}
}
}
Console area:
How many names you want to take: 3
Enter your name: Enter your name: Saon
Enter your name: Srabon
Names are:
Names are: Saon
Names are: Srabon
Invoke input.nextLine() after the input.nextInt() in order to clear the new line character produced by pressing Enter key (when you enter int number);
Alternatively, you can read your int as Integer.valueOf(input.nextLine()).
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Im currently in the process of creating a program and stores data and I'm running into an issue where its printing out a statement twice and counting it as two in an array(its hard to explain so ill show it)
So this is the code
public static void GetData()
{
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
for (int i = 0 ; i < array.length ; i++ )
{
String[] names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
}
for(int j = 0; j < array.length;j++)
{
double[] payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
the problems is its printing out :
How many names do you want to enter?
4
enter employee's name:
enter employee's name:
harry
enter employee's name:
larry
enter employee's name:
mary
enter employee's payrate:
twice right away so when the user declares let says the array size of 4 it'll print that twice and it'll count that as two spots already so now it only counts 3 of the data and switches to the next array, I'm honestly not sure whats causing this, I tried to debug it but it tells me nothing, any help would be loved!
The first names[i] = input.nextLine(); will read the \n from the line containing the number which you read with input.nextInt(), so you'll get an empty name there.
You could read the num as follows:
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
This is a very basic question but I have just started out with JAVA and have hit a bit of a bump with regards to arrays.
What I am trying to do is populate an array with 6 pieces of information from the user:
Number of employees to be input,
An alphanumeric employee number,
A first name,
A last Name,
the number of hours they have worked,
a number input corresponding to Pay Scale.
So far I have gotten these inputs into an array in JAVA however what I wanted to do was use corresponding number input to select a constant within the Pay Scale array and then use that constant to calculate the wages of each employee.
for instance employee 1 worked 10 hours at scale 0 so that would be 10*4.50
and employee worked 10 hours at scale 1 which would be 10*4.62
import java.util.Arrays; //imports Array utility
import java.util.Scanner; //imports Scanner utility
public class test1 {
static Scanner keyb = new Scanner(System.in); //Adds a keyboard input
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
for (int i = 0; i < Employee.length; i++) {
System.out.print("Enter Employee Number: ");
Employee[i] = scanner.next();
System.out.print("Enter Employee's First name: ");
FirstName[i] = scanner.next();
System.out.print("Enter Employee's Last name: ");
LastName[i] = scanner.next();
System.out.print("Enter Employee's Hours worked: ");
HoursWorked[i] = scanner.nextDouble();
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
}
for (int i = 0; i < HoursWorked.length; i++) {
System.out.println("Employee " + Employee[i] + " " + FirstName[i] + " " + LastName[i] + " has "
+ HoursWorked[i] * PayScale[0]);
}
}
}
}
Am I even close to a solution on this?
Is what I'm asking possible in JAVA?
Maybe I'm just looking at this the wrong way, but any help regarding this would be greatly appreciated.
edit
OK I added the extras array into the code
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
int[]PayScale2 = {0,1,2,3,4};
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
I'm just unsure as to where I'd index the original PayScale array with the
PayScale[PayScale2[i]]
would it go into the for statement codeblock? (I have tried putting it in there however I get an error that it's not a statement :/
change
+ HoursWorked[i] * PayScale[0]);
to
+ HoursWorked[i] * PayScale[i]);
apart from that seems to me like you're doing what you're saying you should be doing..
you already have the payscales from here: double[] PayScale = {4.50,4.62,4.90,5.45,6.20}; so the following doesn't make a lot of sense:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
First of all, if you want to keep this number (Number 0 to 4) separately, you should use another Array, not the one where you keep the Payscales, then you could index to the first array which keeps the different rates.. or else you could directly use the first array if you know the pay scale for every employee.. in the end it has to do with what you want to do and how you want to do it, but the logic and the tools are there. If you call the 2nd array PayScale2 for example:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale2[i] = scanner.nextDouble();
then you can index to the first array for example:
PayScale[PayScale2[i]]
in which case if the user inputs 0 then PayScale2[i] would be 0 then PayScale[PayScale2[i]] would be PayScale[0] or 4.5 or whatever you set the value equal to at the first array
I am having trouble coding a hw program that is made to generate test with multiple choice and essay questions. Everything works except my program skips lines when it goes to read a part of the essay class. I know it has to do with the scanner and scan.nextline, scan.nextInt and scan.next, etc but I am confused on how exactly to fix it.
Thank you for your help.
import java.util.*;
public class TestWriter
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String type=null;
System.out.println ("How many questions are on your test?");
int num = scan.nextInt ();
Question [] test = new Question [num];
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next ();
scan.nextLine ();
if (type.equals ("e"))
{
test [i] = new Essay ();
test [i].readQuestion ();
}
if (type.equals ("m"))
{
test [i] = new MultChoice ();
test [i].readQuestion ();
}
}
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1)+": "+ type);
test [i].print ();
}
}
}
here is the essay class
public class Essay extends Question
{
String question;
int line;
public void readQuestion ()
{
System.out.println ("How many lines?");
line = scan.nextInt ();
scan.next ();
System.out.println ("Enter the question");
question = scan.nextLine ();
}
public void print ()
{
System.out.println (question);
for (int i=0; i <line; i++)
System.out.println ("");
}
}
Using scan.nextInt() will generate the following problems
If your input is "5 5", nextInt() will get the next integer leaving the remaining " 5" of the buffer line. Of which the remaining " 5" will be caught by
type = scan.next();
In the class test writer:
System.out.println("How many questions are on your test?");
int num = scan.nextInt();
Question[] test = new Question[num]; for(int i=0; i<num; i++)
{
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
This will generate the issue as i have mentioned above.
To fix this you can either
a) Ensure that input is solely a number
b) Get the entire line like so String temp = scan.nextLine(); then convert it to a integer. This will you can play with the string and check if its the input you require i.e if the 1st letter / set of numerical digits is an e/m or an integer.
The problem with scan.nextInt() is that it only gets the next integer of the input line. If there are spaces after the input it was taken from i.e "5 5" it will grab only the next int 5 and leave " 5" behind.
Thus i would recommend using scan.nextLine() and manipulating the string to ensure that the input can be handled and verified and at the same time ensuring that you do not get confused of where the scanner is at.
You should use .next() / .nextInt() if you are handling an input with various parameters you want to specifically catch such as "25 Male Student 1234" in this case the code would be as such
int age = scan.nextInt();
String sex = scan.next();
String job = scan.next();
int score = scan.nextInt();
Your readQuestion function should be ...
public void readQuestion()
{
System.out.println("How many lines?");
line = scan.nextInt();
scan.nextLine();
System.out.println("Enter the question");
question = scan.nextLine();
}
It should be scan.nextLine(); to add an empty new line at the end
In your TestWriter.main() method what are you expecting at 3 line in following code:
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
scan.nextLine(); //LINE 3: What are you expecting user to enter over here.
the control flow will stuck at this point unless you enter something on the console.