import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
我想要这个类的用户输入并且 带入另一个类并使用数字变量 如果语句
最佳答案
I want the user input from this class and bring into another class and use the number variable for a If statement.
很简单,看一下下面的示例(确保将两个类添加到一个包中不同的 java 文件,如 Player.java 和 ExampleClass.java ),
这是 Scanner
具有的类:
import java.util.*;
public class Player{
public static void main (String [] args){
Scanner getInput = new Scanner(System.in);
System.out.print("Input a number");
//you can take input as integer if you want integer value by nextInt()
String number = getInput.nextLine();
ExampleClass obj = new ExampleClass(number);
obj.checkMethod();
}
}
这是检查号码的类:
public class ExampleClass{
int number;
public ExampleClass(String number){
try{
//If you want to convert into int
this.number = Integer.parseInt(number);
}catch(NumberFormatException e){
System.out.println("Wrong input");
}
}
public void checkMethod(){
if(number > 5){
System.out.println("Number is greater.");
}else{
System.out.println("Number is lesser.");
}
}
}
有几件事要提:
您的示例代码包含语法错误,请先修复这些错误。
- 如果你想要整数,你可以使用
getInput.nextInt()
而不是getInput.nextLine()
。 - 您可以创建 getter 和 setter 来设置值和获取值。在我的示例中,我仅通过构造函数设置值。
- 使用正确的命名约定。
- 在我的示例中,我在构造函数内将
String
转换为整数,并用try
-catch
block 包装以防止NumberFormatException
(如果您输入字符或其他内容,您可以看到错误输入
将打印出来)。有时在不同的情况下,在构造函数中使用try
-catch
并不好。要了解更多信息,请阅读Try / Catch in Constructor - Recommended Practice .
关于java - 我如何从另一个类获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600667/