Java Scanner class reading strings - java

I got the following code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
And the output for that code is the following:
How many names are you going to save:3
Type a name: Type a name: John Doe
Type a name: John Lennon
Notice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
or just read the line and parse the value as an Integer.
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}

use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine()
sc.nextLine()

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.
Here a small change that you can do:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}

This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().
Here is my code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}

You could have simply replaced
names[i] = in.nextLine(); with names[i] = in.next();
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

Related

How do I store tokens into their own element in a given array?

I am trying to write a method that will use StringTokenizer to break up a user inputted String by a single space and store each word into their own array. The given code is as far I have gotten before getting stuck for 3 hours. I am trying to test out the code by having the for loop print out the elements of the array but all it does is return null for every element. What am I doing wrong? My best guess is that it is not assigning the array index to a token but I am not sure.. Any help would be amazing. Thank you!
Also, I know StringTokenizer is old legacy stuff but my professor strictly stated that he wants us to use it.
Thanks
private void receiveInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
int number = st.countTokens();
String tokenArray[] = new String[number];
for (int i = 0; i < tokenArray.length; i++) {
System.out.println(tokenArray[i]);
}
}
String array tokenArray is initialized with size of tokens, but elements in the array are not assigned with values
require
tokenArray[i] = st.nextToken();
amended code
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
int number = st.countTokens();
String tokenArray[] = new String[number];
for (int i = 0; i < tokenArray.length; i++) {
tokenArray[i] = st.nextToken();
System.out.println(tokenArray[i]);
}
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

Why there is an InputMismatchException in my code

System.out.print("Input the number of persons: ");
Scanner scanner = new Scanner(System.in);
int noOfP = scanner.nextInt();
Person[] person = new Person[noOfP];
String name;
int age;
for(int i = 0; i < person.length; i++){
System.out.println("Input name for guest: ");
name = scanner.nextLine();
System.out.println("Input age for guest: ");
age = scanner.nextInt();
person[i] = new Person(name,age);
}
I just wanted to initialize the Person array and set the name and age, but it throws an InputMismatchException at line age = scanner.nextInt();
When you ask for the number of persons, the user isn't just typing a number, they're also inserting a line terminator into the input stream. So when you ask for the name, you're not getting the name, you're getting the line terminator just before the name. And then when you do the .nextInt() for the age, you're finally getting the name. So the first thing you need to do is add scanner.nextLine() after you read the value of noOfP to skip that line terminator. That will fix things through the age of the first person. And then things will start breaking again.
You do the same thing when you ask for age: you invoke scanner.nextInt(), leaving another line terminator in the stream. You need another scanner.nextLine() after that so things don't blow up on the second person.
The code will look like this:
System.out.print("Input the number of persons: ");
Scanner scanner = new Scanner(System.in);
int noOfP = scanner.nextInt();
scanner.nextLine();
Person[] person = new Person[noOfP];
String name;
int age;
for(int i = 0; i < person.length; i++){
System.out.println("Input name for guest: ");
name = scanner.nextLine();
System.out.println("Input age for guest: ");
age = scanner.nextInt();
scanner.nextLine();
person[i] = new Person(name,age);
}
When you hit enter after scanner.nextInt(), the ending newline character is never removed. I've always found it easiest to use Integer.parseInt(scanner.nextLine()) instead of scanner.nextInt() for this reason; these problems never occur.

How to read the user inputs(including spaces) line by line with Scanner?

I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();

get input from user and store it in String Array in Java

i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}

Written data from scanner to arrays [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
I would like to create a shopping list program, after entering the name and price of product enters them into the arrays and then print the entire list of what is wrong with this code?
import java.util.Scanner;
import java.util.Arrays;
public class List {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
}
}
You can resolve it by using nextLine() instead of nextDouble(). However, you need to parse it to a double as your value declared as double :
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = Double.parseDouble(sc.nextLine()) ;
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
Scanner#nextLine() reads the whole line.
Scanner#nextDouble() reads the next token and not the whole line.
So for the second iteration of loop nextLine() will read the same line where you placed the token giving you empty in name[1] and error for double[1]=sc.nextDouble().
Docs
The problem can be solved by adding a nextLine() after reading double variable
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
if(i<name.length-1)
sc.nextLine(); //will skip the line
}
Demo
So I was using input.nextDouble() and it was giving me Type mismatch error
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[4];
String [] name = new String[4];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter product price");
numbers[i] = Double.parseDouble(input.nextLine());
System.out.println("Please enter product name");
name[i] = input.nextLine();
}
System.out.println(Arrays.toString(name));
System.out.println(Arrays.toString(numbers));
}

Categories

Resources