gpt4 book ai didi

Java,返回字符串错误

转载 作者:行者123 更新时间:2023-12-01 23:23:48 24 4
gpt4 key购买 nike

我对编程很陌生,而且还很年轻。

我没有 friend /家人可以帮助我,所以我在互联网上寻求帮助。我的代码有问题,因为它没有按我的预期工作。

它没有打印出变量“TheChoice”的内容,而是结束了。

这不是全部代码,我对其进行了精简,以便更容易阅读,也许更多的人能够快速回答。

但是,这绝对是我搞砸的代码部分)。

public String Choices(String value1, String value2)
{
Scanner x = new Scanner(System.in);
if(x.next() == value1){return value1;}
if(x.next() == value2){return value2;}
}


// Separate class...

ChoiceClass Object1 = new ChoiceClass();
String TheChoice = Object1.Choices("Ham", "Cheese");
System.out.println(TheChoice);

最佳答案

您的代码存在许多问题。

  • 首先,将 String== 进行比较,而不是使用 equals (有大量关于String比较和Object相等的文献在Java中,我建议你看一下herehere .
  • 其次,您并不总是在 choices 方法中返回值。您的方法必须返回一个String(即使是其默认值,如null),但除了给定参数之外,您不考虑用户输入.
  • 此外,您的 Scanner next 也无法工作,因为您调用了两次,当您只想调用它一次时。
  • 最后,您应该看一下 Java 命名约定:方法名称是camelBack。请参阅here用于代码约定。

这里的一个片段可能会对您有所帮助:

public static String choices(String value1, String value2) {
Scanner x = new Scanner(System.in);
System.out.println("Type your choice and ENTER...");
String input = x.nextLine();
if (input.equals(value1)) {
return value1;
}
else if (input.equals(value2)) {
return value2;
}
// handling other user inputs
else {
return "nothing";
}
}

public static void main(String[] args) {
// usage of method. Note that you could also refactor with varargs, as in:
// String... values in method signature.
// This way you could iterate over values and check an arbitrary number of values,
// instead of only 2.
System.out.println(choices("foo", "bar"));
}

输出:

Type your choice and ENTER...

...然后根据输入选择“foo”或“bar”或“nothing”。

关于Java,返回字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314312/

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