Printing first and last name
Hi I just wanted to ask how do I get Java to print the surnames of the names being entered into the scanner?
Name of student?
Ian Smyth
How many attendences did Ian achieve?
65
Name of student?
Jane Asher
How many attendences did Jane achieve?
80
Name of candidate?
Harry Redknapp
How many attendences did Harry achieve?
45
Student Attendance Statistics
Maximum possible attendance: 85 days
Student Attendance %
Ian 65 76.47058823529412
I have pasted my code below
Code:
public static void main(String[] args) {
// TODO code application logic here
Scanner scanner = new Scanner(System.in);
int daysIn1 = 0;
int daysIn2 = 0;
int daysIn3 = 0;
double total = 0.85;
String studentName1;
System.out.println("Name of student?");
studentName1 = scanner.next();
scanner.nextLine();//clear scanner buffer
System.out.println("How many attendences did "+studentName1+" achieve?");
daysIn1 = scanner.nextInt();
scanner.nextLine();//clear scanner buffer
String studentName2;
System.out.println("Name of student?");
studentName2 = scanner.next();
scanner.nextLine();//clear scanner buffer
System.out.println("How many attendences did "+studentName2+" achieve?");
daysIn2 = scanner.nextInt();
scanner.nextLine();//clear scanner buffer
String candidate3;
System.out.println("Name of candidate?");
candidate3 = scanner.next();
scanner.nextLine();//clear scanner buffer
System.out.println("How many attendences did "+candidate3+" achieve?");
daysIn3 = scanner.nextInt();
scanner.nextLine();//clear scanner buffer
System.out.println("Student Attendance Statistics\n");
System.out.println("\tMaximum possible attendance: 85 days\n");
System.out.println("\tStudent\tAttendance\t%\n");
System.out.println("\t"+studentName1+"\t\t"+daysIn1+"\t\t"+daysIn1 / total );
}
}
Thanks
Martyn
Re: Printing first and last name
Scanner#next() gets the next token available to the Scanner object -- the next string before you reach white space or the end of input. So you're only reading in the first name by using next:
Code:
studentName1 = scanner.next();
Better to use Scanner#nextLine() which reads to the end of the line:
Code:
studentName1 = scanner.nextLine();