Java Scanner not accepting input after the For loop - java

I am currently working on a program that requests input for the names and scores of two teams. When I request input for the name and 9 scores of the first team, the scanner accepts input just fine. However, after the for loop, the scanner does not accept input for the name of the second team. This is not the entire program, but I have included all the code up until the point where it is giving me trouble. I suspect that it may have something to do with the for loop because team2 accepts user input just fine when I place it before the for loop.
import java.util.Scanner;
public class sportsGame{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String team1;
String team2;
int team1Scores[] = new int[9]
int team1Total = 0;
int team2Scores[] = new int[9];
int team2Total = 0;
System.out.print("Pick a name for the first team: ");
team1 = input.nextLine();
System.out.print("Enter a score for each of the 9 innings for the "
+ team1 + " separated by spaces: ");
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
System.out.print("Pick a name for the second team: ");
team2 = input.nextLine();
}
}

Scanner's nextInt method does not skip a line, only fetches the int. So when the first loop ends, there is still one newline character left and your input.nextLine() returns a blank string. add a input.nextLine() after your loop to skip this blank line and to solve your problem like this:
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
input.nextLine();
//rest of your code

Related

Scanner takes user-inputted integer, then takes array of Strings, but skips first String inputted

I am using a Scanner object to take user input. The Scanner first takes an integer called 'num'. I then create an array of Strings of size 'num' and I fill this array with Strings taken in by the same Scanner via a for-loop. My problem is that when taking the first String value, the Scanner seems to 'skip' it by assigning it an empty String. Why is it doing this?
import java.util.Scanner;
public class KrisKindle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many people are there?");
int num = scan.nextInt();
String[] names = new String[num];
for(int i = 0; i < names.length; i++) {
System.out.println("Enter name of person " + (i +1) + "/" + num);
names[i] = scan.nextLine();
}
}
}
Here's a sample output for when this program is run:
How many people are there?
7
Enter name of person 1/7
Enter name of person 2/7
Adam
Enter name of person 3/7
Eve
Enter name of person 4/7
What I have tried so far:
Creating a separate Scanner object for taking my array of Strings. This causes a separate error that I can share if it might help
Printing the value of name 1/7 (it is empty)
You just need to add scan.nextLine() after scan.nextInt() because the Scanner.nextInt method doesn't read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline.
You will encounter a similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself)
public class KrisKindle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many people are there?");
int num = scan.nextInt();
scan.nextLine(); // This line you have to add (It consumes the \n character)
String[] names = new String[num];
for(int i = 0; i < names.length; i++) {
System.out.println("Enter name of person " + (i +1) + "/" + num);
names[i] = scan.nextLine();
}
}
}

How can I fix string matrix index problem?

I'm trying to store name and address of persons in the form of 2d array, but when I run my code it accepts less values only. For example if I give the array 2 rows and 2 columns, it accepts only 3 values.
I've tried searching on other forums, couldn't get the proper answer.
I also changed the dimension values but it gives wrong result only.
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
You read 4 values but one is an empty line from when you press enter for int addr=scan.nextInt();
A quick fix is to read that empty line
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
---> scan.nextLine();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
Edit:
Or you can use scanner.skip Skip newline character while reading from Scanner class
In addition to the other answer here is how your code should look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int iPeople = scanner.nextInt();
System.out.print("Enter the number of address: ");
int iAdresses =scanner.nextInt();
scanner.nextLine();
String data[][] = new String[iPeople][iAdresses];
for(int i=0; i < iPeople; i++)
{
for(int j=0; j < iAdresses; j++)
{
System.out.printf("Enter %d address for person %d:%n", j + 1, i + 1);
data[i][j] = scanner.nextLine();
}
}
And try to follow these conventions:
Use proper Java naming conventions
Make your code more readable by providing appropriate empty lines between lines you feel are too cluttered or belong to different groups based on what operation are they trying to accomplish.
If you want to understand why, the behavior of nextLine is explain here : Java Scanner doesn't wait for user input
You can also replace nextLine by next to avoid this.

Why can't I enter another string after the first time in a for loop?

I want to create a program that allows me to enter name, age, and year of birth for 5 different people. However, I get a problem where I cannot enter another name after I entered the first in my for loop. Here is my code:
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
}
}
The program works fine when I run it, but it will not allow me to enter the other 4 names after I entered the first. Here is the output I am getting:
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
names[i] = keyboard.next();
Take a look- I've fixed your code- added "keyboard.nextLine();" at the end.
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
keyboard.nextLine();
}
}
The reason you need to add it is that "nextInt()" will only read what you've entered and not the rest of the line. What's left of the line will be then read by "names[i] = keyboard.nextLine();" automatically.
By putting another "keyboard.nextLine()" at the end, I've skipped what left of the line and then "names[i] = keyboard.nextLine();" gets a new line to read input from.
Every beginner in Java encounters this problem sooner or later :)

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

Arrays and input

My assignment asks me to write a program that will let the user input 10 players' name, age, position, and batting average. The program should then check and display statistics of only those players who are under 25 years old and have a batting average of .280 or better, then display them in order of age.
I've written my code for the input section (where it'll store them in an array):
static int players[] = new int [10];
static String name[] = new String [10];
static double average [] = new double [10];
static int age[] = new int [10];
static String position[] = new String [10];
//method to input names of Blue Jays
public static void inputInfo() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < players.length; i++)
{
System.out.println("Enter player information.");
System.out.println("Input first and last name: ");
name [i] = br.readLine();
System.out.println("Input position: ");
position[i] = br.readLine();
System.out.println("Input batting average (e.g. .246): ");
String averageString = br.readLine();
average [i] = Double.parseDouble(averageString);
System.out.println("Input age: ");
age[i] = br.read();
System.out.println(" ");
}
}
My problem is the input. For the first player I input it shows me this (as it should):
Input first and last name:
John Smith
Input position:
pitcher
Input batting average (e.g. .246):
.300
Input age:
27
But my second input skips the name section completely and jumps to the position input. I can't really figure out why it's doing this! Can anyone help me out? Thanks in advance!
The read method reads only a single character of input; the rest of the line you've entered remains in the stream.
When the next loop starts, readLine detects that it can read the rest of the line already, so it does with no user input. It thinks the user input is already given.
For the input age, use readLine instead of read, and you can use Double.parseDouble to convert the resulting String input to a double.
When you read in the age here:
System.out.println("Input age: ");
age[i] = br.read();
the newline from the user pressing <Enter> is still there. So, when you go back and do
System.out.println("Enter player information.");
System.out.println("Input first and last name: ");
name [i] = br.readLine();
the newline is still in the buffer and will be read in here.
read() only reads a single character at a time. When you press after entering your age, it appends a new line character to the end which triggers the .readLine() for name.
System.out.println("Input age: ");
age[i] = Integer.parseInt(br.readLine());

Categories