gpt4 book ai didi

java - 从某个点记忆一个方法

转载 作者:行者123 更新时间:2023-11-30 07:49:32 24 4
gpt4 key购买 nike

我想在满足条件 (else) 时从某个点重新运行此方法,我知道我需要为其创建一个新的类/方法,但不确定如何创建,因为我的所有变量都保留在 main 方法中。

import java.util.*;

public class OddsAndEvens {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Let's play a game called Odds And Evens");

System.out.println();

System.out.println("What is your name? ");

//user name
String name = input.nextLine();

System.out.println("Hi " + name + "Which do you choose? Odds or Evens ?");

//user preference this is where I want to rerun the method from in else condition
String pref = input.nextLine();


if (pref.equals("Odds") || pref.equals("odds")) {

System.out.println(name + " has picked odds ! Computer will be evens");

} else if(pref.equals("Evens") || pref.equals("evens")) {
System.out.println(name + " has picked evens! Computer will be odds");
} else {
System.out.println("please enter a valid answer");

}
}
}

最佳答案

有很多方法可以做到这一点,一种方法是按照 Valentin 所说的那样做,只创建一个您可以记忆起来的方法。您也可以只使用一个 while 循环,它不断询问“赔率”或“赔率”,直到用户输入两者之一。类似的东西:

    String pref = "";

while(!pref.equalsIgnoreCase("odds") && !pref.equalsIgnoreCase("evens")) {
pref = input.nextLine();
if (pref.equals("Odds") || pref.equals("odds")) {
System.out.println(name + " has picked odds ! Computer will be evens");

} else if (pref.equals("Evens") || pref.equals("evens")) {
System.out.println(name + " has picked evens! Computer will be odds");
} else {
System.out.println("please enter a valid answer");
}
}

您可以通过任何方式缩短代码并使其更清晰,但您应该了解主要思想。

关于java - 从某个点记忆一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com