import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
我想从这个类用户输入和 带入另一个类,并使用数量可变的 如果声明如何从另一个类获取字符串?
import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
我想从这个类用户输入和 带入另一个类,并使用数量可变的 如果声明如何从另一个类获取字符串?
我想从这个类的用户输入,并把到另一个类和 使用数量可变的if语句。
它是简单的看看下面的例子(确保在一个封装不同的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()
。String
整数构造函数中,并与try
包裹 - catch
块从NumberFormatException
以防止(如果你输入文字或东西,你可以看到wrong input
将打印)。有时在变化的情况下,在构造函数中使用try
- catch
并不好。要了解更多信息,请阅读Try/Catch in Constructor - Recommended Practice。您通常做的其他类的导入,只需导入Player类和它应该工作
我不知道如果我得到它,我想你正在使用扫描仪。 这是我会做的方式:
Scanner类:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insert a decimal:");
String inputValue = scanner.nextLine();
if(!new ScannerCalc().isNumeric(inputValue)){
System.out.println("it's not a number...");
break;
}
else
new ScannerCalc().checkNumber(inputValue);
}
}
}
ScannerCalc类:在类的重用方法实例
public class ScannerCalc {
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
public void checkNumber(String number){
if(Integer.parseInt(number)%2==0)
System.out.println("it' even");
else
System.out.println("it's odd");
}
}
留意。
如果您想在另一个实体中使用局部变量,最好将它作为参数传递给其他实体的方法。例如
OtherClass.operation(scanner.nextLine()); // In case method is static
new OtherClass().operation(scanner.nextLine()); // In case method is not static
请提供更多信息。 – Blasanka
'Text'似乎是一个类,'nextLine'是一个成员变量,是吗?如果它是你初始化对象的地方?或者它是'Scanner'类'nextLine()'? – Blasanka
是的,我正在使用扫描仪和是的 –