英文:
why i can't add elements to the array?
问题
public class Assignment12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int grade[] = new int[3];
String name[] = new String[3];
for (int i = 0; i < 3; i++) {
System.out.println("Enter Student name");
String studentName = input.nextLine();
name[i] = studentName;
System.out.println("Enter Student grade");
int studentGrade = input.nextInt();
grade[i] = studentGrade;
}
}
}
英文:
I'm doing my homework, the teacher asked us to store student names and student grades out of 100. And should ask the users to enter the names and the grades. no error the code but when I run the file, it just asks me for the name for only once. But no problem like this with adding to the grade array? What could cause that to happen? What should be done to be able to enter names?
public class Assignment12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int grade[] = new int[3];
String name[] = new String[3];
for (int i = 0; i < 3; i++) {
System.out.println("Enter Student name");
String studentName = input.nextLine();
name[i] = studentName;
System.out.println("Enter Student grade");
int studentGrade = input.nextInt();
grade[i] = studentGrade;
}
}
}
答案1
得分: 0
你可以尝试下面的代码。
Scanner scan = new Scanner(System.in);
int[] marks = new int[3];
String[] names = new String[3];
// 输入分数
for (int i = 0; i < 3; i++) {
marks[i] = scan.nextInt();
}
// 输入回车字符,以便读取字符串
scan.nextLine();
// 循环读取姓名
for (int i = 0; i < 3; i++) {
names[i] = scan.nextLine();
}
// 打印分数
for (int i = 0; i < 3; i++) {
System.out.println(marks[i]);
}
// 打印姓名
for (int i = 0; i < 3; i++) {
System.out.println(names[i]);
}
英文:
You can try this code below.
Scanner scan = new Scanner(System.in);
int[] marks = new int[3];
String[] names = new String[3];
//input marks
for(int i = 0; i < 3; i++) {
marks[i] = scan.nextInt();
}
//for Enter key character as input, in order to read the strings
scan.nextLine();
//loop to read names
for(int i = 0; i < 3; i++) {
names[i] = scan.nextLine();
}
//for printing out marks
for(int i = 0; i < 3; i++) {
System.out.println(marks[i]);
}
//for printing out names
for(int i = 0; i < 3; i++) {
System.out.println(names[i]);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论