Как проверить и использовать входные данные из другого метода

#java

#java

Вопрос:

Я создаю игру, и в конце игры я хочу, чтобы она вызывала пользователя по имени, которое он ввел,, это код, который у меня есть.

 private static final Scanner console = new Scanner(System.in);

public static void main(String[] args) {// follow the prompts.//

    System.out.println("Hello user! what is your name? ");
    String Name = console.nextLine();
    System.out.println("Really? "   Name   " is too weird to be a real name.");
    confirmation();
    Mascot();
    System.out.println("Thank you for playing the demo");

    console.close();
}

public static void confirmation() {

    System.out.print("is that REALLY your name? (type Y/N) ");
    String yN = console.nextLine();
    String a = yN;
    if (a.toLowerCase().contains("y")) {
        System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
    } else {
        calledIt();
    }

}

public static void calledIt() {

    System.out.println("I knew it!");
    System.out.print("whats your real name? ");
    String realName = console.nextLine();
    System.out.println(
            ""   realName   " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");

}

public static boolean Mascot() {

    System.out.println("what Is our school mascot?");
    String b = console.nextLine();
    if (b.toLowerCase().contains("tiger")) {
        System.out.println("Good, next riddle.");
        System.out.println("What runs around the whole yard without moving?");
        String c = console.nextLine();
        if (c.toLowerCase().contains("fence")) {
            System.out.println("Good, next riddle.");
            System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
            String d = console.nextLine();
            if (d.toLowerCase().contains("man")) {
                System.out.println("You, have sucsefully passed the third riddle");
                return true;
            } else {
                System.out.println("You have failed");
                return false;
            }

        } else {
            System.out.println("You have failed");
            return false;
        }
    } else {
        System.out.println("You have failed");
        return false;
    }
}
 

Я хочу, чтобы в конце было напечатано * имя пользователя *, что вы успешно прошли третью загадку.
но он должен быть в состоянии выдержать сохранение первого имени или использование этой последовательности.

 public static void calledIt() {

    System.out.println("I knew it!");
    System.out.print("whats your real name? ");
    String realName = console.nextLine();
    System.out.println(
            ""   realName   " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");

}
 

и если он был активирован, он должен использовать новое имя.

Комментарии:

1. Заставить ваш метод (ы) возвращать строку?

2. Другой вариант — переместить объявление Name out на уровень КЛАССА (в то же место, где объявлена ваша console переменная) и сделать его СТАТИЧЕСКИМ: private static String name; . Затем измените String Name = на Name = . Теперь вы можете получить доступ к этой Name переменной из всех методов, чтобы либо извлечь ее, либо обновить.

Ответ №1:

  1. Измените возвращаемый тип calledIt() на String и верните realName из этого метода
  2. Измените возвращаемый тип подтверждения() на String . Инициализируйте строку (имя строки = null). В части else присвоите этой строке значение, возвращаемое из calledIt() (имя строки = calledIt()). Возвращаемое имя.
  3. В main, если значение, возвращаемое из confirmation(), не равно null, обновите Name этим новым значением.
  4. Передайте имя в качестве входных данных в метод Mascot. Для этого вам необходимо обновить метод Mascot, чтобы он принимал строку в качестве входных данных.

Ответ №2:

Вы можете передать переменную в confirmation() и calledIt() следующим образом

 public static void main(String[] args) {// follow the prompts.//

    System.out.println("Hello user! what is your name? ");
    String Name = console.nextLine();
    System.out.println("Really? "   Name   " is too weird to be a real name.");
    confirmation(Name);
    Mascot();
    System.out.println("Thank you for playing the demo");

    console.close();
}
    
public static void confirmation(String name) {
    
        System.out.print("is that REALLY your name? (type Y/N) ");
        String yN = console.nextLine();
        String a = yN;
        if (a.toLowerCase().contains("y")) {
            System.out.println("I still dont belive you, so you will have to answer 3 riddles before you can continue to the game");
        } else {
            calledIt(name);
        }
    
    }

     public static void calledIt(String realName){
            System.out.println("I knew it!");
            System.out.print("whats your real name? ");
            System.out.println(
                    ""   realName   " sounds like a real name, but you lied the first time so you will need to answer riddles 3 to continue to the game");
        
        }
 

Ответ №3:

Вы могли бы внести следующие изменения:

 public static void main(String[] args) { // follow the prompts.//
    System.out.println("Hello user! What is your name? ");
    String name = console.nextLine();
    System.out.println("Really? "   name   " is too weird to be a real name.");
    System.out.print("Is that REALLY your name? (type Y/N) ");
    String yN = console.nextLine();
    String a = yN;
    if (a.toLowerCase().contains("y")) {
        System.out.println("I still don't believe you, so you will have to answer 3 riddles before you can continue to the game");
    } else {
        System.out.println("I knew it!");
        System.out.print("Whats your real name? ");
        name = console.nextLine();
        System.out.println(
            ""   name   " sounds like a real one, but you lied the first time so you will need to answer riddles 3 to continue to the game");
    }

    mascot(name);
    System.out.println("Thank you for playing the demo");

    console.close();
}

public static boolean mascot(String name) {

    System.out.println("what Is our school mascot?");
    String b = console.nextLine();
    if (b.toLowerCase().contains("tiger")) {
        System.out.println("Good, next riddle.");
        System.out.println("What runs around the whole yard without moving?");
        String c = console.nextLine();
        if (c.toLowerCase().contains("fence")) {
            System.out.println("Good, next riddle.");
            System.out.println("What goes on four feet in the morning, two feet at noon, and three feet in the evening? ");
            String d = console.nextLine();
            if (d.toLowerCase().contains("man")) {
                System.out.println(name   ", you have successfully passed the third riddle");
                return true;
            } else {
                System.out.println("You have failed");
                return false;
            }

        } else {
            System.out.println("You have failed");
            return false;
        }
    } else {
        System.out.println("You have failed");
        return false;
    }
}
 

Комментарии:

1. Это неправильный подход, поскольку он не отвечает на вопрос

2. Привет @WillEvers! Пожалуйста, дважды проверьте описание вопроса: я хочу, чтобы в конце было напечатано * имя пользователя *, вы успешно прошли третью загадку. но он должен иметь возможность сохранять первое имя или использовать эту последовательность. Итак, основное изменение здесь: System.out.println(name ", you have successfully passed the third riddle"); который будет печатать имя игрока после решения всех шагов.

3. вопрос в том, «Как проверять и использовать входные данные из другого метода?»

4. @WillEvers Мне действительно нужен ответ на этот вопрос так, чтобы он соответствовал тому, что сказал Алекс