Question

Program segment works ok but is skipping the first task in the if statement.

The output is as follows if user has selected "Y"

Do you wish to add another subject code - Y or N?
y

Enter the subject name:
Enter subject code:

abc123

It is not giving the user the chance to enter the subject name. It worked before creating the if statement, so I am assuming it has something to do with that. I have been wracking my brain but to no avail.

 System.out.println("Do you wish to add another subject code  - Y or N?  ");
    String response = input.next();

    if (response.equalsIgnoreCase("Y")) {

    /**User input*/

    System.out.println("\nEnter the subject name: ");
    String subjectName = input.nextLine();
    System.out.println("\nEnter subject code: ");
    String subjectCode = input.next();
    Subject mySubject = new Subject(subjectCode, subjectName);

    /**Write to the file*/
    output.println(mySubject.getSubjectCode() + " " + mySubject.getSubjectName());
    output.close();
    }
    else  
      output.close();

    System.out.println("\nProgram terminated\n");

Cheers, Susan

Was it helpful?

Solution

String response = input.next();     // Wrong
String response = input.nextLine(); // Right

When you do input.next(), you just read the first word of the line.

When you afterwards do input.nextLine(), you read up until the next line feed.

That means that if you type y<enter>, the first statement will read y and the second statement will read up until the <enter> which is just the empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top