Returning char into main method
我的程序的目标有点像命运之轮,用户会猜测一个词组的字母。这些字母将按猜测显示。我才刚刚开始,在将字符返回到main方法时遇到了问题。我知道还有其他制作此程序的方法,但是我的教授希望我们使用一种" getguess"方法。该方法应该接受用户输入并确认它是小写字符。由于某些原因,我无法弄清楚该怎么做。我已尝试复制该程序。
谢谢,
导入java.util.Scanner;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Program09 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String phrase; System.out.print("Enter a common phrase:"); phrase=stdIn.next(); int sum=0; getGuess(stdIn); } public static char getGuess(Scanner stdIn) { char LetterGuess; do{ System.out.println("Guess a letter:"); LetterGuess=stdIn.next(); } while(isLowerCase(LetterGuess) == false) return LetterGuess; } } |
在您的程序中,您将返回LetterGuess(应以小写字母L开头),但在主程序中,您不会在任何变量中收到它。
我认为您的第一步应该是使用以下内容:
1 2 |
对于初学者来说,那么您只需要更改逻辑即可读取多个猜测
First of all, you should start your variable name with lowercase letter.
At your line where you get the char from console...
1 | LetterGuess=stdIn.next(); |
返回一个字符串,因此您必须将其转换为char ...
1 | letterGuess=stdIn.next().trim().charAt(0); |
,并且在您的while条件下,行应为...
1 |
In your main method, save the returned char in a variable and then do what you want to do with that...
尝试以这种方式思考:方法是一些计算块,可以选择接受一些输入并可以选择返回一些输出。我们一直在使用现实生活中的方法:
1 2 3 4 5 6 | if(washing machine is available){ washed_clothes = use_washing_machine(dirty_clothes) wait(40 minutes) dried_clothes = use_dryer(washed_clothes) clean clothes = fold(dried_clothes) } |
因此,您要做的是将用户输入收集在