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');
}
那么正确的语法是什么,这是可能的。 Java新手
答案 0 :(得分:0)
首先,不需要循环,你可以删除它。并且您错误地使用了return语句。你不能回来
System.out.println();
此外,您的方法被声明为返回void
,这意味着什么。这意味着你的return语句不需要任何其他内容,只需返回单词。
return;
所以我的建议是首先打印东西,然后return
。你应该真的读Barry Burd的Java for Dummies。
答案 1 :(得分:0)
首先,您无法从void
方法返回任何内容,而是将其更改为char
,例如:
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)).
}
}
然后在main方法(或调用select()
的方法)上添加:
char selection;
selection = select();
System.out.println(selection);
如果您想将switch
添加到循环中(do-while
,就像您的问题一样),那么您可能希望在main方法上这样做:
char selection;
do {
selection = select();
System.out.println(selection);
} while (selection != '0');
但是我强烈建议您阅读Java Docs:Switch Statement和Returning a Value from a method,这实际上是您尝试实现的目标。
从第二个链接,您可以确认我之前说过的内容(在我的回答的第一行和其他一些用户的评论中说明)
声明为void的任何方法都不会返回值。