0

everytime I keyed in Y at the end of the do-while loop, it will not let me key-in for the "Enter name for appointment" I tried changing c = input.next(); to c = input.nextLine(); but is still didnt work. WHy? please help

import java.util.Scanner;
import APP.*;
public class AppointmentTest
{
public static void main(String[] args)
{
    Appointment app = new Appointment();
    String m, y;
    double st, et;
    //char c;
    String c;
    Scanner input = new Scanner (System.in);

    do
    {
        System.out.print("Enter name for the appointment :");
        m = input.nextLine();
        app.setName(m);
        System.out.print("Enter day appointment :");
        y = input.nextLine();
        app.setDay(y);
        System.out.print("Enter start time :");
        st = input.nextDouble();
        app.setStartTime(st);
        System.out.print("Enter end time :");
        et = input.nextDouble();
        app.setEndTime(et);
        System.out.println("Duration of appointment :");
        System.out.print("Do you have any other appointment? (Y/N) :");
        //c = input.next().charAt(0);
        c = input.next();


    }while (c != "N" && c != "n");

}

}

  • Don't use `!=` or `==` to compare strings in Java - `while (c != "N" && c != "n")` does not work. See: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jesper Mar 26 '20 at 08:48
  • @Learnerrrr - I hope the solution worked for you. Let me know if you are still facing the issue. – Arvind Kumar Avinash Mar 26 '20 at 08:51

1 Answers1

0

The operators != or == check the equality of references; not the equality of content. You need to use .equals or .equalsIgnoreCase (for case insensitive comparison).

Do it as follows:

    c = input.nextLine();

} while (!c.equalsIgnoreCase("N"));

Also, replace

st = input.nextDouble();

with

st = Double.parseDouble(input.nextLine());

The same is applicable for et = input.nextDouble(). Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72