0

I need my array to be dynamic, as long as the user enters/deletes elements. The array can't have the length already defined or ask the user the length. For example the user decides to add 5, the array would be: {5}, then the user adds 34 {5,34}, then deletes 5, {34}. Is there a way of doing it? i've been trying with list but when i used if the remove one didn't work and when i use switch with this code it says "unreachable statement". Here's the code so far:

List<String> list = new ArrayList<>();
        Scanner stdin = new Scanner(System.in);

        do {
            System.out.println("Current  " + list);
            System.out.println("Add more? (1) delete one? (2) exit (3)");
            int a= stdin.nextInt();  
            
            switch(a){
                case 1:
                System.out.println("Enter: ");
                list.add(stdin.next()); 
                break;
                case 2:
                System.out.println("Enter: ");
                list.remove(stdin.next());
                break;
                case 3:
                break;
                default:
                break;
            }
            
        } while (true);
        
        stdin.close();
        System.out.println("List is " + list);
        String[] arr = list.toArray(new String[0]);
        System.out.println("Array is " + Arrays.toString(arr));
1
  • You have an infinite loop which you never break out of of. Your break statements only end the execution of the switch not the do .. while, hence all code beneath } while(true); cannot be reached. You could use a flag switch = false and set it to true within your case 3 and then use while(!exit) to make the code reachable. Commented Apr 28, 2022 at 16:44

2 Answers 2

1

You can try to use label. So basically the break in your case 3 only breaks outside switch statement but not outside the do while loop. You can add a statement before do as below:

outerloop:
do{
  switch(a){
  // rest of your logic
  case 3:
  break outerloop;
  }
}
while(true)

where outerloop is a label. Please try this.

Sign up to request clarification or add additional context in comments.

Comments

0

I think there's a problem with your while statement. When you use the break keyword, it refers to your switch statement. So you'll never reach the end of your loop.

Try something to implement something to break the loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.