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

标签 java loops while-loop

我是 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/

相关文章:

java - 该算法中使用了什么数据结构?

java - token "finally"上的语法错误,删除此 token 并且方法 readStream(InputStream) 未定义类型 ParkActivity

java - 如何添加锁以从文件方法读取和写入

c++ - 无限 while 循环和 for 循环有什么区别?

java - 硬币变化递归方法

javascript - 生成时间戳日期范围之间的空数据 | JavaScript

python - 猜谜游戏中输入多个相同的数字;循环停止工作?

bash - 在第一行之后停止读取行循环时的Shell脚本

python - 尝试使用 Python 代码确定生物体的 "height"

javascript - 如何在 JavaScript 中使用循环函数声明变量 x1、x2、...、x10?