gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:39:40 25 4
gpt4 key购买 nike

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/

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