4 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
問(wèn)題是您正在使用兩個(gè)不同的對(duì)象。第一個(gè)在方法中創(chuàng)建,第二個(gè)在方法中創(chuàng)建。您僅為方法中的對(duì)象初始化播放器名稱。它們永遠(yuǎn)不會(huì)在第二個(gè)對(duì)象中初始化。Gamemain()greetPlayer()main()
我假設(shè)您只想使用一個(gè)對(duì)象。一種解決方案是將對(duì)象傳遞給方法:GameGamegreetPlayer()
public static void main(String[] args) {
Welcome.greet();
Game start = new Game();
start.inputName();
Welcome.greetPlayer(start);
start.show();
}
public static void greetPlayer(Game call){
System.out.println("Welcome " + " " + call.x + " and " + call.y + "\n" + "Have Fun!");
}
另一種選擇是將名稱直接傳遞給方法:greetPlayer()
public static void main(String[] args) {
Welcome.greet();
Game start = new Game();
start.inputName();
Welcome.greetPlayer(start.x, start.y);
start.show();
}
public static void greetPlayer(String player1, String player2){
System.out.println("Welcome " + " " + player1 + " and " + player2 + "\n" + "Have Fun!");
}

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是因?yàn)樵?code>Game call = new Game();greetPlayer()
你有一個(gè)新的 Game 實(shí)例,所以你失去了輸入的 和。x
y

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊
您正在兩個(gè)地方創(chuàng)建 的對(duì)象。Game()
在 main() 中:
Game start = new Game();
在 :greetPlayer()
Game call = new Game();
您可以嘗試合并兩個(gè)類,這樣您就可以在一個(gè)類中引入玩家,獲取名稱和游戲的其余部分:
import java.util.Scanner;
public class TicTac {
public static void main(String[] args) {
Game start = new Game();
Game.greet();
start.inputName();
start.show();
}
}
class Game {
public String x, y;
public void inputName() {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name Player 1:");
String player1 = input.nextLine();
System.out.println("Enter your name Player 2:");
String player2 = input.nextLine();
x = player1;
y = player2;
}
public static void greet() {
System.out.println("\tTicTac Game By Abhi:");
System.out.println("\t __X_|__O_|__X_");
System.out.println("\t __O_|__X_|__O_");
System.out.println("\t X | O | X");
}
public void show() {
System.out.printf("Hi %s and %s", x, y);
}
}

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
您需要將 Game 類的實(shí)例作為參數(shù)傳遞到對(duì) greetPlayer 函數(shù)的調(diào)用中。試試下面這樣:start
import java.util.*;
public class TicTac{
public static void main(String[] args) {
Welcome.greet();
Game start = new Game();
start.inputName();
Welcome.greetPlayer(start);
start.show();
}
)
class Welcome{
public static void greetPlayer(Game call){
System.out.println("Welcome " + " " + call.x + " and " + call.y + "\n" + "Have Fun!");
}
}
添加回答
舉報(bào)