简体   繁体   English

无法在其他类别中使用扫描仪字符串输入

[英]Not able to use Scanner String input in other class

I am working on a program that has two classes. 我正在开发一个有两个类的程序。 Class 1 contains a constructor called "Probability" that takes three inputs: a String and two doubles. 类1包含一个名为“概率”的构造函数,该构造函数接受三个输入:一个String和两个double。 This code is shown below: 该代码如下所示:

public Probability(String inputString, double inputDouble1, double inputDouble2) {
    this.inputString = inputString;
    this.inputDouble1 = inputDouble1;
    this.inputDouble2 = inputDouble2;
}

There is also a modifier that has five conditionals depending on the String that is fed in (ie if this.inputString == "String1"...), with a catch for invalid inputs. 还有一个修饰符,它具有五个条件,具体取决于输入的字符串(即this.inputString ==“ String1” ...),并带有无效输入的捕获。 Class 2 calls the "Probability" constructor multiple times to create probabilities I need for my program. 类2多次调用“概率”构造函数以创建程序所需的概率。

So here's my dilemma. 所以这是我的难题。 There are five String inputs that I need to be able to enter based on whatever I'm doing. 我需要根据自己的操作输入五个String输入。 Before, I was going into my Class 2 code and changing all of the references to this String manually (the references were "String1", "String2", etc...). 之前,我进入了第2类代码,并手动更改了对该String的所有引用(引用为“ String1”,“ String2”等)。 In other words, the code looked something like this: 换句话说,代码看起来像这样:

Probability P1 = new Probability("String1", double1, double2);

This is obviously a pain when you have twenty references. 当您有二十个引用时,这显然是很痛苦的。 So I wanted to use a Scanner to take user input in order to change all of the references at once when I run my Main. 因此,我想使用扫描仪获取用户输入,以便在运行Main时立即更改所有引用。 The user would enter String1 when prompted, and then the input would be set equal to a String variable. 提示时,用户将输入String1,然后将输入设置为等于String变量。 This is my new code, where double1 and double2 are previous Scanner user inputs: 这是我的新代码,其中double1和double2是以前的Scanner用户输入:

Scanner scan = new Scanner(System.in);

System.out.print("Please enter a string: ");
String userInput = scan.nextLine();
Probability P1 = new Probability(userInput, double1, double2);

But this doesn't work. 但这是行不通的。 I get the error that I've set up in my catch in the Class 1 modifier that says the input doesn't match any of the strings in the conditionals. 我收到我在Class 1修饰符中捕获的错误,该错误说输入与条件语句中的任何字符串都不匹配。 I have tried the inputs String1 and "String1". 我已经尝试了输入String1和“ String1”。 Does anyone have any ideas why this may be? 有谁知道为什么会这样吗? I have no issues with the double inputs fed from Class 2 into the Class 1 modifier. 对于从Class 2输入到Class 1修饰符的双重输入,我没有任何问题。

是的,我的朋友和其他人一样,建议您必须使用equals方法比较两个字符串,而不是使用==运算符,这用于引用匹配而不是内容匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM