带对象的基本程序(java)

时间:2016-02-29 14:13:37

标签: java object

我想创建询问姓名和年龄的程序,然后在我的屏幕上打印。但我正在试验“toString”方法和对象。

当我运行我的程序时,我输入姓名,姓氏和年龄,它会中断并显示消息:

"Exception in thread "main" java.util.IllegalFormatConversionException: d != tutorial35Composition.Banana
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
    at java.util.Formatter$FormatSpecifier.print(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.lang.String.format(Unknown Source)
    at tutorial35Composition.Apple.toString(Apple.java:13)
    at java.lang.String.valueOf(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at tutorial35Composition.Main.main(Main.java:24)
"

代码是:

package tutorial35Composition;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String name;
        String surname;
        int age;
        Scanner input = new Scanner(System.in);
        System.out.println("Type your name: ");
        name = input.nextLine();
        System.out.println("Type your surname: ");
        surname = input.nextLine();
        System.out.println("Type your age: ");
        age = input.nextInt();

        Banana banana = new Banana(age);
        Banana banan = banana;
        Apple apple = new Apple(name,surname,banan);
        Apple appl;
        appl = apple;
        System.out.println(appl);
    }

}


package tutorial35Composition;

public class Apple {
    String Name;
    String Surname;
    Banana Age;
    public Apple(String name,String surname,Banana age){
        Name = name;
        Surname = surname;
        Age = age;
    }
    public String toString(){
        return String.format("Your name is %s, your surname is %s and your age is %02d", Name, Surname, Age);
    }
}

package tutorial35Composition;

public class Banana {
    int age;
    public Banana(int Age){
        age = Age;
    }
    public String toString(){
        String Age2;
        Age2 = age + "";
        return Age2;
    }
}

3 个答案:

答案 0 :(得分:4)

Java String格式的API表示%d代表:

  

结果格式为十进制整数

一个香蕉不是一个整数(我最后说的很激动)。

您可以为age Banana属性实现getter,并调用该getter,而不是将整个Banana实例传递给您的格式化程序。

API here

答案 1 :(得分:3)

您无法将Banana打印为整数,但可以在该类中打印age

    return String.format("Your name is %s, your surname is %s and your age is %02d", 
           Name, Surname, Age.age);

顺便说一句,你应该用小写字母开始变量名。例如namesurnameage

答案 2 :(得分:0)

您试图打印的对象不是其成员,您可以这样做,或者您可以使用getter方法来获取值。

public String toString()
{
  return String.format("Your name is %s, your surname is %s and your age is 
  %02d", Name, Surname, Age.age);
}

在香蕉课中使用Getters

public int getAge(){
    return age;
 }