为什么我不能向数组中添加元素?

huangapple go评论75阅读模式
英文:

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 &lt; 3; i++) {
      System.out.println(&quot;Enter Student name&quot;);
      String studentName = input.nextLine();
      name[i] = studentName;

      System.out.println(&quot;Enter Student grade&quot;);
      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 &lt; 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 &lt; 3; i++) {
		names[i] = scan.nextLine();
}
//for printing out marks
for(int i = 0; i &lt; 3; i++) {
	System.out.println(marks[i]);
}
//for printing out names
for(int i = 0; i &lt; 3; i++) {
	System.out.println(names[i]);
}

huangapple
  • 本文由 发表于 2020年9月17日 16:28:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63934164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定