我有一个Employee类:
public class Employee{
private String firstName;
private String lastName;
private double salary;
private double rate;
public Employee(String firstName, String lastName, double salary){
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public double getSalary(){
return salary/1000;
}
public double setSalaryIncrease(double rate){
if ((rate-1)*100>=0){
this.rate = ((rate-1)*100);
return this.rate;
}
else{
this.rate = -((rate-1)*100);
return this.rate;
}
}
public String toString(){
return firstName+" "+lastName+": salary is "+String.format("%.0f", salary/1000)+"K, annual raise is "+String.format("%.0f", rate)+"%";
}
}
在我的主班级
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
Employee employee = new Employee(sc.next(), sc.next(), sc.nextDouble());
employee.setSalaryIncrease(sc.nextDouble());
System.out.println(employee);
}
}
}
例如,如果我有输入列表,例如
Mohammad Ali 24000.0 1.11
Steve Gates 36000.0 1.05
Michael Jordan 71000.0 1.07
我希望仅在扫描完所有3个输入后才打印它。但是,我最终是在扫描完每一行后得到每行打印的,即
穆罕默德·阿里24000.0 1.11
穆罕默德·阿里(Mohammad Ali):薪水为24000,年薪为11%
史蒂夫·盖茨36000.0 1.05
史蒂夫·盖茨(Steve Gates):薪水为3.6万,年薪为5%
在不更改主类的情况下,如何修改toString()方法以在读取所有输入后将其整体打印出来?
答案 0 :(得分:0)
System.out.println();在换行中打印每个字符串
尝试System.out.print(“ string”) 在while循环之后,您可以使用 System.out.println(“”)跳到新行