簡體   English   中英

我應該怎么做才能使我的 do-while 循環語句起作用?

[英]what should I do to make my do-while loop statement work?

我創建了一個程序,詢問學生的姓名、年份和他們的課程。 這個想法是如果我按 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.");
}
}

我的建議是將“另一個”設置為布爾值

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。

您必須將比較運算符==更改為字符串等於 ex another.equals("Y") 或者你不能放置相同的案例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM