gpt4 book ai didi

java - 添加环回以及字母输入

转载 作者:行者123 更新时间:2023-12-01 08:52:22 26 4
gpt4 key购买 nike

我是 Java 新手,并且正在尽我所能学习。我正在做一项作业,该作业需要考试成绩并将其转换为字母成绩。我为此编写代码没有问题,事实上,它按原样运行得很好。

import java.util.Scanner;
public class grades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
byte Score;
Scanner keyboard = new Scanner(System.in);
//Start program
System.out.println("Welcome to the automated grading system!");
{
System.out.println("Please enter your exam score from 0-100. Press 'E' to Exit");
}
Score = input.nextByte();
{
if(Score >= 90 && Score <= 100) {
System.out.println("Your Grade is an A.");
} else if (Score >= 80 && Score <= 89) {
System.out.println("your Grade is a B.");
} else if (Score >= 70 && Score <= 79) {
System.out.println("Your Grade is a C.");
} else if (Score >= 60 && Score <= 69){
{System.out.println("Your Grade is a D.");}
}else if (Score < 50){{
System.out.println("Your Grade is a F.");}
}}
}
}

我遇到的问题是用户输入字符“E”而不是数字。除了我已有的之外,我该如何添加它?另外,我试图让程序在输入数字后循环并重新开始,但第一条消息只是一遍又一遍地重复。
所以我需要知道如何实现这一点。
我知道我必须建立一个 boolean 值,但我不确定将 while 语句放在哪里。

最佳答案

The problem I am having a hard time with is with the users's input of a character 'E' instead of a number.

您可以读取字符串而不是字节。当您实际需要时,将字符串转换为整数。

Also, I am trying to make the program loop back and start over once I enter a number

尝试 while-true 并在需要时中断。

I know I have to establish a boolean but not sure where to put the while statement at

围绕您想要重复的所有内容。

例如

Scanner sc = new Scanner(System.in);
String input = "";
while (true) {
System.out.println("Please enter your exam score from 0-100. Press 'E' to Exit");
input = sc.next();
if (input.equals("E")) break; // exit loop

int score = Integer.parseInt(input);
// check score

}

关于java - 添加环回以及字母输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42306639/

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