java - 我如何从另一个类获取字符串?

标签 java string user-input

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.javaExampleClass.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.");
        }
    }
}

有几件事要提:

您的示例代码包含语法错误,请先修复这些错误。

  1. 如果你想要整数,你可以使用 getInput.nextInt() 而不是 getInput.nextLine()
  2. 您可以创建 getter 和 setter 来设置值和获取值。在我的示例中,我仅通过构造函数设置值。
  3. 使用正确的命名约定。
  4. 在我的示例中,我在构造函数内将 String 转换为整数,并用 try-catch block 包装以防止 NumberFormatException (如果您输入字符或其他内容,您可以看到错误输入将打印出来)。有时在不同的情况下,在构造函数中使用 try-catch 并不好。要了解更多信息,请阅读Try / Catch in Constructor - Recommended Practice .

关于java - 我如何从另一个类获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600667/

相关文章:

php - 如何清理字符串以避免 SQL 注入(inject)和最常见的攻击类型? (在 PHP 中)

java - 如何用java创建hastebin

具有前端的 Java 简单分析/事件流处理

javascript - startsWith() 检查不同的字母或字符串

python - 如何在一个字符串中一次替换两个东西?

python - 如何反转字符串中单词的顺序

java - ".0"在双重计算中产生的差异

java - Eclipse 上的 Glassfish 。收集要安装的项目时发生错误

c++ - 结束数组输入(C++ 行业标准)

python - 如何控制用户的输入