【问题标题】:Java, cannot tell what is going wrong? VERY basic code [duplicate]Java,不知道出了什么问题?非常基本的代码[重复]
【发布时间】:2013-10-27 23:14:54
【问题描述】:

我正在尝试在一行代码中打印出整个“f”变量。f 显然代表女性,但是当我使用我的代码方式时它显示错误?

对不起,我是初学者。

import java.util.*;

class university {
    public static void main(String[] args){
            Scanner scanner = new Scanner(System.in);
            Person2 mPerson, fPerson = null;`

        String fFirstName, fSurname, mFirstName, mSurname;
        int fAge, mAge;

        System.out.println("Please enter the firstname of your favourite female author");
        fFirstName = scanner.nextLine();
        System.out.println("Please enter her second name");
        fSurname = scanner.nextLine();
        System.out.println("Please enter her age");
        fAge = scanner.nextInt();
        scanner.nextLine();

        System.out.println("Please enter the firstname of your favourite female author");
        mFirstName = scanner.nextLine();
        System.out.println("Please enter her second name");
        mSurname = scanner.nextLine();
        System.out.println("Please enter her age");
        mAge = scanner.nextInt();

        fPerson = new Person2(fFirstName, fSurname, fAge);

        System.out.print(fPerson);
    }
}

【问题讨论】:

  • 什么错误? fPerson2 是如何定义的?
  • 没有“fperson2”
  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 始终复制/粘贴错误和异常输出。
  • 天啊,对不起。 person2 是如何定义的?如果你不花时间格式化你的代码,事情就会被误读。
  • 我搜索了"how to print a class in Java",你猜怎么着?

标签: java


【解决方案1】:

您遇到的问题是您没有阅读任何有关 Java 的教程,并且您试图解决即将出现的问题。

您面临的问题是您没有声明计算机获取您期望他拥有的信息的地方。编码不是一件神奇的事情,你得到你写的东西。

您缺少的是在您的 Person2 类中实现 toString() 方法。

@Override
public String toString() {
 return fFirstName 
}

不要浪费更多时间来解决平台问题并尝试阅读trial

【讨论】:

    【解决方案2】:

    实现 Person 类的 toString() 方法,只打印对象不会打印值。

    public String toString() {
       //format the way you want the values to be printed
       return fFirstName + " " + fSurname + " " + fAge;
    }
    

    【讨论】:

    • 类名是Person2,需要加上@Override
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多