我希望它能够打印出来:"你的分数是第一个",但它不会。
我使用toString()
,我完全是Java的初学者。如果有人有任何想法,请告诉我。
我的代码:
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int i)
{
this.name = name;
this.age = i;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int pie;
Scanner input1 = new Scanner(System.in);
String ass;
pie = input.nextInt();
System.out.println("Your Score is " + pie);
ass = input1.nextLine();
System.out.println("Your name is " + ass);
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 1) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person(ass, pie) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people,
Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
我的期望是: 它打印&#34;你的分数是:&#34;第一 我可以输入我想要的信息。
答案 0 :(得分:0)
输入乐谱后按Enter键时,您应该阅读&#39; nextLine&#39;等待下一次输入。
Scanner input = new Scanner(System.in);
int pie = input.nextInt();
input.nextLine();
String ass = input.nextLine();
input.close();
System.out.println("Your Score is " + pie);
System.out.println("Your name is " + ass);
注意:最好在读取流后关闭扫描仪。
答案 1 :(得分:-1)
I want it to print: "Your score is first", but it won't.
由于您在打印邮件之前询问scanner
输入,因此不会先打印
<强>溶液强>
System.out.println("Your Score is " + pie);
pie = input.nextInt();
System.out.println("Your name is " + ass);
ass = input1.nextLine();