使用方法的java决策
Task:
- Includes Decisions, and all constructs above.
- Defines and uses methods including one(s) that take an argument and return a result
Example: As above, but the program now has a series of possible template lines to go in the love letter in addition to the above and chooses which one to include at random. For example it might choose between a line of the form “You are my <noun>” and a line “I will forever think of you as my <noun>”. The person running the program inputs a noun when asked (eg “snugglebunny”) to complete the sentence (e.g., in this case it might then choose “You are my snugglebunny”). For each template, a separate method is defined that returns the full sentence given the word supplied as an argument.
这是我设法完成的代码,但是它显示错误“String[]无法转换为printmessage(ans1,input)的String”。我不知道我在这个问题上哪里出了问题,如果有人能帮忙,我会很高兴的
public static void decisions()
{
String input;
String phrase = "";
input = askquestion (); // defining the method for asking user the question to input a noun word.
String [] ans1 = {"You remind me of my","I always think of you as my","I wish You could always be my","you are my one and only"}; // this will randomly select one phrase out of 4 given
int rand = (int) (Math.random() * 4); //this will do a random math calculation and select one phrase
switch (rand)
{
case 0:
printmessage(ans1, input);
break;
case 1:
printmessage(ans1, input);
break;
case 2:
printmessage(ans1, input);
break;
case 3:
printmessage(ans1, input);
break;
}
// this defines the method for printing the message, taking the argument strings inside the bracket to the message defined later on.
} // END decisions
public static String askquestion ()
{
String result = "";
result = JOptionPane.showInputDialog("Enter a noun word to describe your partner"); //asks users input
return result;
}
public static void printmessage (String ans1, String input) // this will receive the argument from the method defined above and then be printed below as shown. The argument have been declared as x and y.
{
JOptionPane.showInputDialog( ans1 + input ); //this will combine the two variables and execute the message.
}
# 1 楼答案
String[]是字符串数组
printmessage
需要单个字符串,而不是它们的数组。给它一根绳子aka,在switch语句中传入
rand
参数,顺便说一下,这是多余的,因为您调用的是相同的方法可以简单地变成