gpt4 book ai didi

java - 字符串输入未执行

转载 作者:行者123 更新时间:2023-11-30 05:30:04 26 4
gpt4 key购买 nike

我开发了一个代码来获取学生分数的输入详细信息并将平均值打印为输出。此操作将一直执行,直到用户给出“n”作为循环条件的输入。但在我的代码中,用户无法给出条件输入,并且自动执行 while 循环

import java.util.Scanner;


class Student

{

String reg;

int maths,phy,che,cse,avg;

void cal()

{

if(maths<50 | phy<50 | che<50 | cse<50)

{

System.out.println("The grade of the student will not be computed");

}

else

{

avg=((maths+phy+che+cse)/4);

if(avg>=91)

{

System.out.println("S");

}

if(avg>=81 && avg<=90)

{

System.out.println("A");

}



if(avg>=71 && avg<=80)

{

System.out.println("B");

}



if(avg>=61 && avg<=70)

{

System.out.println("C");

}


if(avg>=50 && avg<=60)

{

System.out.println("D");

}



}


}

}







class Main1 //3rd

{

public static void main(String args[]) throws Exception {

Scanner w = new Scanner(System.in);
String r = "Y", a = "Y";

while (r.contains(a)) {

Student s = new Student();
System.out.println("Enter the marks for maths,physics,chemistry,CSE along with your Reg.no first");
s.reg = w.nextLine();
s.maths = w.nextInt();
s.phy = w.nextInt();
s.che = w.nextInt();
s.cse = w.nextInt();
System.out.println("press 'Y' to continue and 'N' to exit");
a = w.nextLine();
s.cal();

}

}

}

实际输出:

C:\Program Files\Java\jdk-12.0.2\bin>java Main1

Enter the marks for maths,physics,chemistry,CSE along with your Reg.no first

100

100

100

100

100

press 'Y' to continue and 'N' to exit

S

Enter the marks for maths,physics,chemistry,CSE along with your Reg.no first

最佳答案

请在System.out.println("press 'Y' to continue and 'N' to exit");之前添加w.nextLine();,这样main 方法应该如下所示:

public static void main(String args[]) throws Exception {
Scanner w = new Scanner(System.in);
String r = "Y", a = "Y";

while (r.contains(a)) {

Student s = new Student();
System.out.println("Enter the marks for maths,physics,chemistry,CSE along with your Reg.no first");
s.reg = w.nextLine();
s.maths = w.nextInt();
s.phy = w.nextInt();
s.che = w.nextInt();
s.cse = w.nextInt();
w.nextLine(); //------> Added
System.out.println("press 'Y' to continue and 'N' to exit");
a = w.nextLine();
s.cal();

关于java - 字符串输入未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754705/

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