【问题标题】:what should I do to make my do-while loop statement work? [duplicate]我应该怎么做才能使我的 do-while 循环语句起作用? [复制]
【发布时间】:2021-12-14 04:18:49
【问题描述】:

我创建了一个程序,该程序会询问学生的姓名、年份和所修课程。这个想法是,如果我按 y(yes),它应该循环返回并询问另一个学生,但在我的情况下,如果我输入 y,它不会问我。对初学者有什么建议吗?

import java.util.Scanner;

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

Scanner scan = new Scanner(System.in);
String studentName, another;
int year,choice;

do{
System.out.println("Student name: ");
studentName = scan.nextLine();
System.out.println("Year: ");
year = scan.nextInt();
System.out.println("\t1.BSIT \n\t2.BSCS \n\t3.BSCpE \n\t4.BSN");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
if(choice == 1) {
    System.out.println("Course is BSIT");
}
else if(choice == 2 ) {
    System.out.println("Course is BSCS");
}
else if(choice == 3 ) {
    System.out.println("Course is BSCpE");
}
else if(choice == 4) {
    System.out.println("Course is BSN");
}
System.out.println("Another Student? type Y if yes, and N if no");
another = scan.nextLine();
}while((another == "Y") || (another == "y"));
        if ((another == "N") || (another == "n"))System.out.println("You are the last student.");
}
}

【问题讨论】:

  • 你能发布你的输入案例吗

标签: java loops while-loop do-while


【解决方案1】:

我的建议是将“另一个”设置为布尔值

boolean anotherStudent = false;
do
{


if((another.equals("Y") || (another.equals("y") ){
anotherStudent = true;
else if((another.equals("N")  || (another.equals("n") ){
anotherStudent = false;
}while(!anotherStudent)

如果他们不输入 Y 或 N,我也会做 else if for。

【讨论】:

    【解决方案2】:

    您必须将比较运算符 == 更改为字符串等于 ex another.equals("Y")。或者你不能找到same case

    【讨论】:

    • 好的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多