gpt4 book ai didi

java - while 循环,为 java 中的下一个 while 循环存储值

转载 作者:行者123 更新时间:2023-12-02 08:59:37 25 4
gpt4 key购买 nike

我是 Java 初学者。我有一个作业要求我从用户那里获取 3 个输入,然后同时输出这 3 个输入。这是我的代码。我只得到 1 个输出。假设看起来像这样:

example任何人都可以帮忙,谢谢!

这是我的代码

Scanner sc = new Scanner(System.in);

int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;


while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();

System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);

i++;
}
System.out.print(classname + ": ");

while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();

最佳答案

我要做的第一件事就是创建一个类(class) POJO(普通旧Java 对象)。它应该有两个字段:name rating。我将在该 Course POJO 中使用 toString 实现显示逻辑。就像,

public class Course {
private String name;
private int rating;

public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}

public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}

然后,您的 main 方法只需在一个循环中填充由三个 Course 实例组成的单个数组,并在第二个循环中显示它们。就像,

Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}

关于java - while 循环,为 java 中的下一个 while 循环存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60257588/

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