简体   繁体   English

我应该怎么做才能使我的 do-while 循环语句起作用?

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

I've created a program that asks students' names, years, and the courses they have.我创建了一个程序,询问学生的姓名、年份和他们的课程。 The idea is if I press y(yes) it should loop back and ask another student, but in my case, if I enter y, it doesn't ask me.这个想法是如果我按 y(yes) 它应该循环并询问另一个学生,但在我的情况下,如果我输入 y,它不会询问我。 Any tips for beginners?对初学者有什么建议吗?

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.");
}
}

My suggestion would be to set 'another' to be a boolean我的建议是将“另一个”设置为布尔值

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)

I would also do a else if for if they dont enter a Y or an N.如果他们不输入 Y 或 N,我也会执行 else if for。

you must change the comparison operator == to string equals ex another.equals("Y") .您必须将比较运算符==更改为字符串等于 ex another.equals("Y") or u cant site the same case或者你不能放置相同的案例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM