gpt4 book ai didi

java - 用户使用扫描仪和阵列进行多个输入

转载 作者:行者123 更新时间:2023-12-01 17:21:01 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序依赖于用户输入来创建学生及其分数。

import java.util.Scanner;

public class Marks {
public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("How many students are there? ");
int n = sc.nextInt();
String [] student = new String[n];

for(int i = 0; i <student.length; i++){
int nextI = i + 1;
System.out.print("Enter name of student " + nextI + ": ");
student[i] = sc.next();

}

我的目标是让程序在用户输入学生姓名后提示一条消息“输入分数:”,但找不到任何网站/帖子来帮助我做到这一点。

最佳答案

您可以使用另一个标记数组并将标记存储在另一个数组中。以下代码可能会有所帮助。

Scanner sc = new Scanner(System.in);
System.out.print("How many students are there? ");
int n = sc.nextInt();
String [] student = new String[n];
String [] marks =new String[n]; // use another array to store marks

for(int i = 0; i <student.length; i++){
int nextI = i + 1;
System.out.print("Enter name of student " + nextI + ": ");
student[i] = sc.next();
System.out.print("Enter Marks for " + student[i] + ": ");
marks[i]= sc.next(); // store marks for the student
}
System.out.println("StudentName Marks");
for(int i=0;i<student.length;i++) {
System.out.println(student[i]+" "+marks[i]);
}

输出:

How many students are there? 2
Enter name of student 1: back
Enter Marks for back: 20
Enter name of student 2: door
Enter Marks for door: 30
StudentName Marks
back 20
door 30

这可以通过Map更有效地完成。自己探索一下,了解更多关于Map的知识尝试使用Map来实现上面的代码

关于java - 用户使用扫描仪和阵列进行多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61289160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com