我今天一直在努力;它是Java代码,因此您可以:输入学生数量,输入他们的名字,姓氏,百分比,然后打印出该百分比是什么(通过/区别)等。
但是由于某些原因,仅对于第一个条目,第一个和姓氏提示都同时出现,因此姓氏被姓氏覆盖,并且甚至不能输入第一个学生的名字。
你能发现问题吗?谢谢。
//imports scanner class
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
// new scanner called sc
Scanner sc = new Scanner(System.in);
// start off by asking:
System.out.print("How many students? ");
// typed in number = number of students
int count = sc.nextInt();
// Line break
System.out.print("\n");
// new strings for name/grade and int for percentage
String fname[] = new String[count];
String lname[] = new String[count];
int percent[] = new int[count];
System.out.println("A-Z for Name & 0-9 for Percentages Only\n");
// if there's input - add the info in
for (int i=0; i<count;i++){
// enter first name
System.out.print("Enter first name: ");
fname[i] = sc.nextLine();
// enter surname
System.out.print("Enter last name: ");
lname[i] = sc.nextLine();
// enter percent
System.out.print("Enter percentage: ");
percent[i] = Integer.parseInt(sc.nextLine());
}
// print out some text for information
System.out.println("\nThe following information displays the students full name, percentage & their grade.");
// and print them on screen
for (int i=0; i<count;i++) {
System.out.print("\nStudent - " + fname[i] + " " + lname[i] + " received " + percent[i] + "%.");
if (percent[i] >= 00 && percent[i] <= 39) {System.out.print(" That's a Fail.");}
if (percent[i] >= 40 && percent[i] <= 64) {System.out.print(" That's a Pass.");}
if (percent[i] >= 65 && percent[i] <= 84) {System.out.print(" That's a Merit.");}
if (percent[i] >= 85 && percent[i] <= 100) {System.out.print(" That's a Distinction.");}
if (percent[i] > 100) {System.out.print(" This percentage is too high? please try again.");}
if (percent[i] < 0) {System.out.print(" This percentage is negative? please try again.");}
}
}
}
答案 0 :(得分:3)
问题是第一个扫描器nextInt()条目。输入数字并按Enter键输入此数据。但是nextInt只是读取整数并且返回的托架仍然保留在输入上。当代码继续执行下一个扫描程序时,nextLine()方法将立即读取返回的托架,因为它仍然在输入上待处理。在此过程中将名字留空。为了避免这种情况,你可以在循环之前调用nextLine()。
您也可以通过始终使用nextLine()并在第一个问题中将结果字符串解析为整数来避免这种情况。
答案 1 :(得分:0)
System.out.print("How many students? ");
// typed in number = number of students
int count = sc.nextInt();
**sc.nextLine();**
// Line break
System.out.print("\n");
你可以添加sc.nextLine();在你的nextInt()调用之后,为了摆脱额外的换行符,当你要求这个名字的时候,你将从一个新的行开始。