3 回答
TA贡献1895条经验 获得超3个赞
我假设您是 Java 新手,因为您似乎不熟悉字段的概念(即您可以将变量放在方法之外)。
public class YourClass {
static String p1;
static String p2;
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
}
TA贡献1786条经验 获得超11个赞
我所要做的就是在外面创建实例/静态变量!像这样:
static String name1;
static String name2;
这很容易。感谢大家的帮助!
TA贡献1828条经验 获得超3个赞
您正在搜索的内容称为实例变量,请查看。 https://www.tutorialspoint.com/java/java_variable_types.htm
添加回答
举报