Home > database >  Question is to create a menu program with options like add, remove ,display and exit. Why my if else
Question is to create a menu program with options like add, remove ,display and exit. Why my if else

Time:11-16

import java.util.*;
import java.util.Arrays; 
import java.util.Scanner;
public class A{
public static void main(String[] args){
ArrayList<Integer> arr=new ArrayList<> ();
arr.add(1);
arr.add(2);
arr.add(4);
arr.add(5);
arr.add(7);
arr.add(9);
arr.add(6);
System.out.println(arr);
Scanner s=new Scanner(System.in);
while(true){
String ADD="ADD";
String Display="Display";
String Remove="Remove";
String Exit="Exit";
System.out.println("Enter what you whish to do= ");
String o=s.next();
{
if(o==ADD){
System.out.println("Enter number= ");
int a=s.nextInt();
arr.add(a);
System.out.println(arr);
}
else if(o==Remove){
System.out.println("Enter number= ");
int i=s.nextInt();
arr.remove(i);
System.out.println(arr);
}
else if(o==Display){
System.out.println(arr);
}
else if(o==Exit){
break;
}
}}}

Question is to create a menu program with options like add, remove ,display and exit by using array list .My if else statement is not working after enter while loop. Loop should be infinite until user input is exit.

CodePudding user response:

IDE display note "String values are compared using '==', not 'equals()'". Try to use o.equals(<your_command_value_variable_name>).

        {
            if (o.equals(ADD)) {
                System.out.println("Enter number= ");
                int a = s.nextInt();
                arr.add(a);
                System.out.println(arr);
            } else if (o.equals(Remove)) {
                System.out.println("Enter number= ");
                int i = s.nextInt();
                arr.remove(i);
                System.out.println(arr);

...

Also, you can use an enum instead of String constants and "switch-case" statement instead of "if-else" or replace constants initialization out of the loop

  • Related