[英]System.out in parameter
我有一个测试文件,根据它我需要构建我的程序,下面是测试文件。 但是,我对s1.showDetails(System.out)感到困惑; 我从未见过System.out的参数可以帮助任何人。 怎么办呢??? 当我尝试编写showDetails()时,编译器会写错误。 我的学生代码在此下方,谢谢!
import java.util.*;
public class Q2 {
public static void main(String [] args)
{
// Start on section A
System.out.println("Question 2");
System.out.println("Start on part A");
Student s1 = new Student("John", "Smith", 42);
s1.showDetails(System.out);
Course cs = new Course("Computer science");
}
}
public class Student {
private String name;
private String familyName;
private int moduleMark;
private int total;
protected Student(String name, String familyName, int moduleMark)
{
this.name = name;
this.familyName = familyName;
this.moduleMark = moduleMark;
}
public String getName()
{
return name;
}
public String getFamilyName()
{
return familyName;
}
public int getModuleMark()
{
return moduleMark;
}
public String showDetails()
{
return (this.name + " " + this.familyName + " " + moduleMark + total);
//print(name);
}
}
该错误本质上意味着编译器找不到名称为showDetails的方法,该方法带有PrintStream
类型的参数。 您无需将System.out
传递给showDetails()
方法。 下面是编写showDetails()
的正确方法。 了解有关System.out的信息 。
public void showDetails()
{
System.out.println(this.name + " " + this.familyName + " " + moduleMark + total);
}
该错误几乎说明了问题所在。
Student类型的showDetails()方法不适用于Q2.main(Q2.java:9)上的参数(PrintStream)
该程序尝试使用碰巧是PrintStream的System.out调用您的方法。 因此,将showDetails更改为
public String showDetails(PrintStream out) {
out.println(this.name + " " + this.familyName + " " + moduleMark + total);
}
这使测试人员(我假设有一个程序可以测试您的分配是否正确)可以为您提供任何PrintStream,可以是System.out或任何其他PrintStream。
您的程序无法编译。
您的主要方法是使用名为showDetails的方法,该方法将PrintStream作为参数(System.out)。 而且,您仅定义了一个没有参数的名为showDetails的方法。
查看System.out的文档 。 与其他系统类一样,它也是一个领域。 确实,它有些特殊,因为它是静态的,但这并不会改变游戏的多少...
因此,编写具有正确参数列表的方法,您将更加接近。
public String showDetails(PrintStream stream) {
//your code here
}
showDetails应该写入传入的参数流。
在学习编程时。 尝试将查询与命令分开 。 这是一个很好的原则:方法应该做一件事:要么使用参数对当前对象做某事,要么回答有关当前对象状态的查询。 不是都。 在这里,您返回一个字符串并需要一个流...您最好将其分成两种方法:一种方法获取字符串,然后第二种方法对该字符串调用stream.write。
public String toString() {
//your code here
}
public void showDetails(PrintStream stream) {
//your code here
}
由于print
是从showDetails
消息中注释掉的,因此有2种明显的解决方案
showDetails
消息并不意味着要打印出任何内容(尽管有名称),而应该只在main方法中将其打印出来
System.out.println( s1.showDetails() );
showDetails
消息应将String打印到任何PrintStream
,然后必须调整该方法的签名以及实现
public String showDetails(PrintStream stream) { stream.println( ... ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.