简体   繁体   中英

How can i use input(int) in get and return method in Java?

so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more. im trying to use the get and return method. i wanted to do this in an input way but i cant use the "int age = person1.GetAge() System.out.println("Age:" + age) because it will become 2 variables (age) i hope you understand my question and i know it sounds stupid but i wanna learn xD.

CODE:


//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give

package practice;
import java.util.Scanner;

class person{
    String name;
    int age;
    
    void speak() {
        System.out.print("Hello my name is:" + name);
    }
    
    int retire() {
        int yrsleft = 65 - age;
        return yrsleft;
        
    }
    int GetAge() {
        return age;
    }
    
}

public class curiosity1{
    public static void main(String[]args) {
        person person1 = new person();
        Scanner input = new Scanner(System.in);
        
        System.out.print("What is your name:");
        String name = input.next();
        
        System.out.print("What is your age:");
        int age = input.nextInt();
        
        
        //person1.name = "John";
        //person1.age = 30;
        System.out.println("Name: " + name);
        
        int age = person1.GetAge();
        System.out.println("Age:" + age);
        

        int years = person1.retire();
        System.out.println("Years till retirement:" + years);
        

    }
}``` 

I hope I understood your question correctly, you want to do this?

person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge()); 

Or you can override toString() method in your class (since all java classes are inherited from Object , which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.

class Person { // always start class name with a capital letter
    int age;
    String name;

    public Person(int age, String name) {
        this.age = age; 
        this.name = name;
    }
    // Your methods and etc.
    @Override
    public String toString() {
        return "Name:" + this.name + ". Age:" + this.age; 
    }
}

And then:

int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM