This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:
public class Test{
private Vector<String> vecStr;
public void run(){
vecStr = new Vector<String>();
System.out.println("How many strings do you want for your string vector?");
int numStr = keyboard.nextInt();
System.out.println("Enter your string values.");
for (int i=0;i<numStr;i++){
System.out.println(i + "Input");
vecStr.add(keyboard.nextLine());}
}
}
}
Let's say I input 4, somehow, the code gives me:
0
1
input:
2
input:
3
input:
It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?
Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.
You can use input stream readers:
Vector<String> vecStr = new Vector<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many strings do you want for your string vector?");
int numStr = Integer.parseInt(reader.readLine());
System.out.println("Enter your string values:");
for (int i=0;i<numStr;i++){
System.out.println(i + " Input: ");
vecStr.add(reader.readLine());
}
System.out.println("vector contains:");
System.out.println(vecStr);
Related
I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }
First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.
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 7 years ago.
I tried to get inputs via scanner and in the past, I use enter to get to the next set of inputs.
For ex.
Input 1 <enter>
Input 2 <enter>
However this time, it only accepts in the same line , taking spaces as delimiter.
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String inputs[]= new String[3];
t = in.nextInt();
in.reset(); //Tried resetting Scanner to see if this works
input_line = in.nextLine();
inputs = input_line.split(" ");
for(String s:inputs)
System.out.println(s);
For instance, I expect to take the variable t in first line and then move on to the second line for input_line scanning. But if I hit enter after entering t, the program ends.
What am I missing here?
(Merging with another question was suggested but , let me explain, the Scanner does not skip any inputs).
Without any testing I would think you would need something like this
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String[] input_numbers = new String[3];
t = in.nextInt();
in.nextLine();
input_line = in.nextLine();
while(!input_line.equals("")){
input_numbers = input_line.split(" ");
// do what you want with numbers here for instance parse to make each string variable into int or create new scanner to do so
input_line = in.nextLine();
}
}
I'm trying to take in a string input which consists of multiple lines of numbers separated by ',' and ';' .
Example:
1,2;3,4;5,6;
9,8;7,6;
0,1;
;
Code:
ArrayList<Integer> alist = new ArrayList<>();
String delims = ";|\\,";
int i = 0;
Scanner input = new Scanner(System.in);
input.useDelimiter(delims);
while (input.hasNext()) {
alist.add(i, input.nextInt());
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
i++;
}
System.out.print('x');
When I run this in eclipse:
1,2;3,4;5,6; ( <= what i typed in console)
321133123413351436153716 ( <= output)
I'd expect something more like:
0 1
1 2
2 3
3 4
4 5
5 6
x
Why am I getting this sort of output?
One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.
So you need to have the user enter something that tells you they are done. For example:
while(input.hasNext()) {
System.out.print("Enter an integer or 'end' to finish: ");
String next = input.next();
if("end".equalsIgnoreCase(next)) {
break;
}
int theInt = Integer.parseInt(next);
...
For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.
And on these lines:
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:
System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");
Or just:
System.out.println(i + " " + alist.get(i));
Edit for comment.
You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:
Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
String nextLine = sysIn.nextLine();
if(nextLine.isEmpty()) {
break;
}
Scanner lineIn = new Scanner(nextLine);
lineIn.useDelimiter(";|\\,");
while(lineIn.hasNextInt()) {
int nextInt = lineIn.nextInt();
...
}
}
Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):
When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.
Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.
int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.
Your code, with the above points addressed becomes as follows:
ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
alist.add(input.nextInt());
System.out.println(i + " " + alist.get(i));
}
System.out.println('x');
Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:
Scanner input = new Scanner(System.in).useDelimiter("\\D");
This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I have problem with Scanner
When I run the program it skips this one after
System.out.println("name");
n1=s.nextLine();
This is the program "CEmploye " is a class
package Ex5_2;
import java.util.*;
public class XXXX {
public static void main(String[] args) {
int input;
int c1 ;
String n1;
Date d1 = null;
float p1;
float [] t = new float[3];
System.out.println("give nb of emp");
Scanner s = new Scanner(System.in);
input=s.nextInt();
Vector v = new Vector(input);
for(int i=0 ;i <input;i++)
{
System.out.println("cin");
c1=s.nextInt();
System.out.println("name");
n1=s.nextLine();
System.out.println("price");
p1=s.nextFloat();
for(int k=0 ; k<3;k++)
{
System.out.println("nb of hour");
CEmploye.tab[k]=s.nextFloat();
}
CEmploye emp = new CEmploye(c1,n1,d1,p1);
emp.CalculSalaire();
System.out.println(emp.salaire);
}
}
}
Can anyone give me solution ?
System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.
You'll need to read everything on a line by itself then parse it (with some validation as needed):
cl = Integer.parseInt(s.nextLine());
and
pl = Float.parseFloat(s.nextLine());
and
CEmploye.tab[k]=Float.parseFloat(s.nextLine());
You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();
nextInt() only reads the next integer available and leaves a newline character in the inputstream.
Your s.nextLine() then gets consumed thus not prompting for additional inputs.
Simply add another nextLine() to read more lines
c1=s.nextInt();
This just reads the integer value not the end of line. So when you do
n1=s.nextLine();
it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am learning Java, and I'm not very far into it, and I don't know why but Java seemed to skip a line. I don't think the code from all my pages is really neccesery so I will just put the first page and the result I get when using it. Thanks!
import java.util.Scanner;
public class First {
public static void main(String args[]){
Scanner scanz = new Scanner(System.in);
System.out.println("Hello, please tell me your birthday!");
System.out.print("Day: ");
int dayz = scanz.nextInt();
System.out.print("Month: ");
int monthz = scanz.nextInt();
System.out.print("Year: ");
int yearz = scanz.nextInt();
System.out.println("Now, tell me your name!");
System.out.print("Name: ");
String namez = scanz.nextLine();
Time timeObject = new Time(dayz,monthz,yearz);
Second secondObject = new Second(namez,timeObject);
System.out.println("\n\n\n\n\n" + secondObject);
}
}
It skips the line
String namez = scanz.nextLine();
Console output: (excuse the birthday bit, it is other stuff)
Hello, please tell me your birthday!
Day: 34
Month: 234
Year: 43
Now, tell me your name!
Name:
My name is and my birthday is 00/00/43
It doesn't give you a chance to give a name, it just skips straight past and takes the name as null. Please, if anyone could, tell me why! I want to learn Java, and this little annoyance is standing in my way.
Thanks!
The problem is that the nextLine gets any characters on the line, and the \n (newline character) is left over from the scanner inputs above.
So instead of letting you enter something new, it takes the \n as the input and continues.
To fix, just put two scanners back to back like this:
System.out.print("Name: ");
scanz.nextLine();
String namez = scanz.nextLine();
Just using:
String namez = scanz.next();
will work too, but will limit the names to be one word. (aka first name only)
I believe the intended use of nextLine is correct. The problem however is that nextInt does not create a newline token, and it's instead reading the rest of that line (which is empty). I believe that if another nextLine statement would be added after that, the code would work. Next on the other hand only recognizes the first word so that might not be the correct solution.