gpt4 book ai didi

java - 当我突破内部 if 时,为什么我的消息会打印两次?

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

我的代码有一点问题。编译和运行效果很好,但是,当我尝试打破内部循环时,

System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");

当我只想打印一次时,上面的代码在终端上打印了两次。

我有一种感觉,我的括号对齐方式是一个简单的错误,但我很难弄清楚如何做到这一点。任何帮助将不胜感激!

import java.util.Scanner;

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

Scanner input = new Scanner(System.in);

final int MAX = 15;

int[] homework = new int[MAX];
int[] classwork = new int[MAX];
int[] lab = new int[MAX];
int[] test = new int[MAX];
int[] quizzes = new int[MAX];
int[] midterm = new int[MAX];
int[] fin = new int[MAX];
int hwCount, clCount, labCount, testCount, quizCount, midCount, finCount;
double hwTotal, clTotal, labTotal, testTotal, quizTotal, midTotal, finTotal;
double grade = 0;

String selection = "";

System.out.println();
System.out.println("Welcome to GetGrade!");
System.out.println();

while (true) {

System.out.println("Type which category you want to add to.");
System.out.println("Homework, Classwork, Labs, Test, Quizzes, Midterm, Final");
selection = input.nextLine();

if (selection.equals("homework")) {

System.out.print("What percentange of your grade is homework? > ");
double hwPercent = input.nextDouble();
System.out.println("Now begin typing your grades. When you are finished, type -1.");

for (int i = 0; i < homework.length; i++) {
homework[i] = input.nextInt();
hwTotal = homework[i] * hwPercent;
grade += hwTotal;
if (homework[i] == -1) break;
}
}
}
}
}

最佳答案

这就像看起来一样微不足道:
调用 input.nextInt();在你的内部循环中不包括换行符。因此,您将打破内循环,接收仅包含 input.nextLine() 中的换行符的下一行;这是“-1\n”行的剩余输入,并再次继续主循环,因为它与“作业”不匹配。

关于java - 当我突破内部 if 时,为什么我的消息会打印两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170073/

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