Home > Software engineering >  what should I do to make my do-while loop statement work?
what should I do to make my do-while loop statement work?

Time:10-29

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

CodePudding user response:

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.

CodePudding user response:

you must change the comparison operator == to string equals ex another.equals("Y"). or u cant site the same case

  • Related