gpt4 book ai didi

java - 为什么当我运行程序时,会显示代码中的所有字母等级选项?我只想显示正确答案

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

我对 Java 编程非常陌生,有人告诉我这是一个很棒的网站,可以将我推向正确的方向。

为什么当我运行程序时,会显示代码中的所有字母等级选项?我只想显示正确的一个。请帮忙。

另外,当输入时,如何让数值显示在同一行而不返回到下一行?

感谢您对 Java 新手的帮助和见解。

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignment_1;

/**
*
* @author
*/

import java.util.Scanner;
public class Assignment_1
{

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("Welcome to the Letter Grade Convertor Program");
System.out.println();

Scanner sc = new Scanner(System.in);

String choice = "y";
while (choice.equalsIgnoreCase("y"))
{

System.out.println("Enter numerical grade: ");
int grade = sc.nextInt();
char letter = 0;
if(grade <= 100 || grade >= 90)
letter = 'A';
System.out.println("Letter grade: " + letter);
if (grade <= 89 || grade >= 80)
letter = 'B';
System.out.println("Letter grade: " + letter);

if (grade <= 79 || grade >= 70)
letter = 'C';
System.out.println("Letter grade: " + letter);

if(grade <= 69 || grade >= 60)
letter = 'D';
System.out.println("Letter grade: " + letter);

if(grade < 60 || grade <=0)
letter = 'F';
System.out.println("Letter grade: " + letter);


System.out.println("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}

最佳答案

如果有多个语句,则应添加大括号。如果您留下括号,则只有第一行属于 if 条件。因此 sout 代码始终会执行。当您添加卷闸时,它是一个 block ,其中的所有行都属于 if 条件。

if(grade <= 100 || grade >= 90){
letter = 'A';
System.out.println("Letter grade: " + letter);
}

始终添加大括号是一个好的做法

但是,正如 @dici 建议您可以在最后打印成绩,而不是在所有 if 条件中添加 out.print

像这样

public static void main(String[] args) {
System.out.println("Welcome to the Letter Grade Convertor Program");
System.out.println();

Scanner sc = new Scanner(System.in);

String choice = "y";
while (choice.equalsIgnoreCase("y")) {

System.out.println("Enter numerical grade: ");
int grade = sc.nextInt();
char letter = 0;
if (grade <= 100 || grade >= 90) {
letter = 'A';
}

if (grade <= 89 || grade >= 80) {
letter = 'B';
}

if (grade <= 79 || grade >= 70) {
letter = 'C';
}

if (grade <= 69 || grade >= 60) {
letter = 'D';
}

if (grade < 60 || grade <= 0) {
letter = 'F';
}
System.out.println("Letter grade: " + letter);

System.out.println("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}

关于java - 为什么当我运行程序时,会显示代码中的所有字母等级选项?我只想显示正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32541504/

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