1 Attachment(s)
Output isn't as expected.
I'm in the process of creating a program that will get information from the user on who all is attending a competition, and then the scores of the teams attending and then it will give the 1st place winner, 2nd place winner and 3rd place winner. But im only on the part where the program will ask the user who is attending and im already having a problem with the output.
Attachment 337
As you see, it skips asking me what the name of school 2 is...
this is my code
Code :
import java.util.Scanner;
public class Competition
{
static Scanner input = new Scanner(System.in);
static School[] Attendee;
static int numSchools;
public static void main(String args[])
{
System.out.print("How many schools are attending the Competition? ==> ");
numSchools = input.nextInt();
Attendee = new School[numSchools];
for (int i = 0; i<numSchools; i++)
{
int realNum = i+1;
Attendee[i] = new School(School.getName(realNum),School.getPlatoon());
}
}
}
class School
{
static Scanner input = new Scanner(System.in);
static String schoolName;
static int havePlatoon;
public School(String n, int p)
{
schoolName = n;
havePlatoon = p;
}
public static String getName(int n)
{
System.out.println();
System.out.println();
System.out.print("What is the name of school number "+n+"? ==> ");
schoolName = input.nextLine();
return schoolName;
}
public static int getPlatoon()
{
System.out.println();
System.out.println();
System.out.print("Does "+schoolName+" have a platoon? (1 for yes, 2 for no) ==> ");
havePlatoon = input.nextInt();
return havePlatoon;
}
}
Re: Output isn't as expected.
The answer boils down to the intricacies of how the scanner works. When calling nextInt, a new line char is still present in the buffer. Calling nextLine again will result in the scanner seeing the new line and returning immediately. Simple fix is to change nextInt into a newLine and parse the integer from there.
Re: Output isn't as expected.
Thank you! it works perfectly now.