[英]java programming trouble with methods
In Java, I just recently went over methods and I wanted to do something to put what I learned into practice. 在Java中,我最近才研究方法,我想做一些事情将自己学到的东西付诸实践。 however, I just got stuck.
但是,我只是被卡住了。
What I am trying to do here is have a print line of "What color is chocolate? 1. White 2. Black. 3. Brown. The answer is " 我要在这里做的是打印一行“巧克力是什么颜色?1.白色2.黑色。3.棕色。答案是“
essentially my goal is to have the print line say "The answer is Brown." 本质上,我的目标是让打印行说“答案是布朗”。
Can I get a few words of advice? 我能得到几点建议吗?
public static void main(String[] args) {
//What color is chocolate? 1. White 2. Black 3. Brown
int corAns = methodChocolate(3);
if (corAns == 3) {
System.out.println("Brown");
}
System.out.println("What color is chocolate? 1. White 2. Black 3. Brown.
The answer is "+corAns);
}
static int methodChocolate(int ans) {
if (ans == 3) {
return 3;
} else if (ans == 2) {
return 2;
} else if (ans == 1) {
return 1;
}
return 0;
}
Change methodChocolate
to return a String
like 更改
methodChocolate
返回一个String
像
static String methodChocolate(int ans) {
if (ans == 3) {
return "Brown";
...
and you call it like this 你这样称呼它
String corAns = methodChocolate(3);
then you should be able to print it correctly. 那么您应该能够正确打印它。
you could do something like this: 您可以执行以下操作:
import java.util.Scanner;
public class example{
public static void main(String[] args) {
//input keyboard
Scanner sc= new Scanner(System.in);
//What color is chocolate? 1. White 2. Black 3. Brown
System.out.println("What color is chocolate? \n1. White \n2. Black \n3. Brown.");
String corAns = methodChocolate(sc.nextInt());
System.out.println("The answer is "+corAns);
}
static String methodChocolate(int n){
switch(n){
case 1:
return "White";
case 2:
return "Black";
case 3:
return "Brown";
default:
return null;
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.