【发布时间】:2015-10-03 17:07:47
【问题描述】:
所以一切正常,但我唯一的问题是我不确定如何从我的speakLine() 方法返回一个数据。我正在尝试打印我从一组问题中得到的正确答案的数量。
类似这样的事情:你在 3 个中得到了“2”个正确。
Public static void main(String[] args) throws Exception {
int cal;
int i;
for (i = 0; i < 3; i++) {
int num1 = randomA();
int num2 = randomB();
cal = num1 + num2;
speakLines(num1, num2, cal);
}
我需要 speakLine 方法()中的“计数”int:
System.out.println("You got " + count + "of " + i + "right");
} // end main()
这是方法
public static void speakLines(int num1, int num2, int cal) {
int count = 0;
Scanner scanner = new Scanner(System.in);
Voice voice;
// set up a Voicemanager object and use it to link voice with a particular voice
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin16");
// load the selected voice
voice.allocate();
// begin speaking the text
System.out.println("what is " + num1 + " + " + num2 + ":");
voice.speak("what is " + num1 + " + " + num2 + ":");
//talk
System.out.println("Please enter answer");
int answer = scanner.nextInt();
//talk
if (answer == cal) {
System.out.println("That's right");
voice.speak("That's right");
count += 1;
"Count +=1" above ^ -- 我需要从 main() 方法打印这个 count int。这是我试图返回到主要方法的数据“计数”。这告诉我用户答对了多少。
} else {
System.out.println("Sorry, the answer is" + cal);
voice.speak("Sorry, the answer is " + cal);
}
} // end speakLines()
public static int randomA() {
int A;
A = 1 + (int) (Math.random() * 10);
return A;
}
public static int randomB() {
int B;
B = 1 + (int) (Math.random() * 5);
return B;
}
// end randomB()
} // end class
现在我知道静态 void 方法不返回数据。但我知道应该有一种方法可以返回特定数据。
【问题讨论】:
-
从外观上看,您可能想阅读this。
-
speakLines必须是static void,还是只是static? -
@frenchDolphin 我想你在问问题,OP 无法回答 :)
-
@turing85 好的,谢谢你的帮助。
标签: java methods int return-value