Search code examples
javastringuser-input

How would I get a String from another class?


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


Solution

  • I want the user input from this class and bring into another class and use the number variable for a If statement.

    It is simple take a look at below example(make sure to add both classes in one package different java files as Player.java and ExampleClass.java),

    This is the class that Scanner has:

    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();
        }
    }
    

    This is the class that check number:

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

    Few thing to mention:

    Your example code contains syntax errors, fix those first.

    1. If you want integer you can use getInput.nextInt() rather than getInput.nextLine().
    2. You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
    3. Use proper naming convention.
    4. In my example I convert the String into integer inside the constructor and wrap with try-catch block to prevent from NumberFormatException(If you input character or something you can see wrong input will print). Sometimes in variaus situation it is not good to use try-catch in constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.