简体   繁体   中英

How do I return the switch statement inside a do while loop using an instance method?

public void select()
{



do
{
  switch(info)
   {
     case'1':
     case'a':
       return System.out.println("Hello");
     case'2':
     case'b':
       return selection = 'b';
     default:
       return System.out.println("Close");
   }
 }while(info != 'b');
}

So what would be the proper syntax and is this the even possible to do. New to Java

First, the loop is not needed, you can delete that. And you are using return statements wrongly. You cannot return

System.out.println();

Also, your method is declared to return void which means nothing. That means your return statement doesn't need anything else,just the word return.

 return;

So my advice is that print the stuff first, and then return . And you should really read Java for Dummies, by Barry Burd.

1st of all you can't return anything from a void method, instead change it to char for example:

public char select () {
    //read user input
    char userInput = '1'; //change it as you wish or read from console
    switch (userInput) {
        case '1':
        case 'a':
            return 'a';
        case '2':
        case 'b':
            return 'b';
        //... and so on
        default:
            return '0'; //Or anything you want (but it MUST be a char (at least for my code, if you change it to String, you can return a word or well... a String)).
    }
}

Then on main method (or the method which called select() ) you add:

char selection;
selection = select();
System.out.println(selection);

If you want to add the switch into a loop ( do-while as in your question), then you might want to do it this way on main method:

char selection;
do {
    selection = select();
    System.out.println(selection);
} while (selection != '0');

However I strongly recommend you to read Java Docs: Switch Statement and Returning a Value from a method which is actually what you're trying to achieve.

From second link you can confirm what I said before (on the 1st line of my answer and as some other users stated on comments)

Any method declared void doesn't return a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM