java method error - java

I have a task to do, which is make a film archive. Here are my tasks:
Besides the main program, create a custom class that stores information about a movie. This class is then used in the main program. The following information should be stored for each film
title
length
grade
format
year
then
In the main program, you should be able to store 1,000 films.
The user should be able to do the following in the program (make a selection menu):
• Enter the information about a movie. Make a method for loading a movie from the user.
• Print the information on all films. Make a method for printing a film and use it.
• Save all your movies to a file. Please do your own method for this.
• Download movies from a file. Please do your own method for this.
The problem is that I got an error with my skrivUtInfo(PrintOut information) method
I create an array list of 1000 films. But how can I print 1000 films?
Here is my code:
public class Film {
String title ;
int length;
int grade ;
String format ;
int year ;
}
import java.util.*;
import java.io.*;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int antal = 1;
film[0] = new Film();
film[0].title = "matrix";
film[0].length = 220;
film[0].grade = 5;
film[0].format = "DVD";
film[0].year = 1999;
while(true)
{
int n = 0;
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if(val.equals("1")){
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next() ;
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt() ;
}
else if (val.equals("2"))
{
skrivUtInfo(film, antal);
/*System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year);*/
}
}
}
public skrivUtInfo (Film[] qwert, int a) {
for (int n=0; n<a; n++) {
System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year) ;
return Film[];
}
}
}

you have to change the method as
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println("title = "+qwert[n].title) ;
System.out.println("length = "+qwert[n].length) ;
System.out.println("grade = "+qwert[n].grade) ;
System.out.println("format = "+qwert[n].format) ;
System.out.println("year = "+qwert[n].year) ;
}
}
also put a bracket here
else if (val.equals("2"))
{
skrivUtInfo(film);
// the comments
}
} //<- you must add this bracket. is from while (i think)
also a tip, in Film class you can override the toString method from class Object
public class Film{
String title ;
int length;
int grade ;
String format ;
int year ;
public String toString() {
return "title = " + title +
"length = " + length +
"grade = " + grade +
"format = " + format +
"year = " + year;
}
}
so the skrivUtInfo becomes
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println(qwert[n]);
}
}
or
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
System.out.println(f);
}
}

If you've learned about java.util.List, you can do it this way:
List<Film> films = new ArrayList<Film>();
films.add(new Film("Amadeus", 120, 5, "DVD", 1984); ); // Add as many as you like
System.out.println(films); // Make sure your Film class overrides toString()
If you haven't, just do it in a loop:
Film [] films = new Film[1000];
films[0] = new Film("Amadeus", 120, 5, "DVD", 1984);
for (Film film : films) {
System.out.println(film); // Make sure you File class overrides toString()
}
You're probably having problems because your Film class is flawed. Do it this way:
public class Film {
private final String title ;
private final int length;
private final int grade ;
private final String format ;
private final int year ;
public Film(String title, int length, int grade, String format, int year) {
this.title = title;
this.length = length;
this.grade = grade;
this.format = format;
this.year = year;
}
public String getTitle() {
return title;
}
public int getLength() {
return length;
}
public int getGrade() {
return grade;
}
public String getFormat() {
return format;
}
public int getYear() {
return year;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Film");
sb.append("{title='").append(title).append('\'');
sb.append(", length=").append(length);
sb.append(", grade=").append(grade);
sb.append(", format='").append(format).append('\'');
sb.append(", year=").append(year);
sb.append('}');
return sb.toString();
}
}

The method public skrivUtInfo (Film[] qwert, int a) has no return type specified. In java either it should have a void or a valid type as return, but i see you returning Film[]. You cannot do that way. You have to declare like
public Film[] skrivUtInfo (Film[] qwert, int a){
....
return qwert;
}
Ultimately since you are just printing the stuff here you don't need to return anything. In that case you should have
public void skrivUtInfo (Film[] qwert, int a){
.....
return;
}
You can have an empty return or no return specified in a method which has a void return type.

I have test this code and works fine. I change a few parts as i thought it should play
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int n = 0;
do {
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if (val.equals("1")) {
film[n] = new Film();
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next();
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt();
n++;
} else if (val.equals("2")) {
skrivUtInfo(film);
}
} while(n < film.length);
}
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
if (f != null)
System.out.println(f);
}
}
}
class Film {
String title;
int length;
int grade;
String format;
int year;
public String toString() {
return "title = " + title + ", length = " + length + ", grade = " + grade
+ ", format = " + format + ", year = " + year;
}
}

Related

why my program don't recognize the .txt file

I try to made a program which print the top 20 frequently words in a text file in java, and i have 3 classes but i don't know why can not compile it help me please. I show you the tree classes just to have an idea:
1)
public class Client {
public static void main(String[] args) {
Map<String, Integer> frequencies = new TreeMap<String, Integer>();
while(file.hasNext()){//Este lazo lee las palabras y crea el TreeMap
String word= clean(doc.next());
Integer count = frequencies.get(word);
if(count==null){
count = 1;}
else {
count = count + 1;
}
}
Object[] Claves = frequencies.keySet().toArray();
Object[] Valores = frequencies.values().toArray();
Par[] par = new Par[frequencies.size()];
for (int i=0;i<frequencies.size();i++){
Par p = new Par(Claves[i].toString(),(int) Valores[i]);
par[i]=p;
}
Arrays.sort(par);
showResult(par);
}
public static void showResult(Par[] arreglo){
System.out.println("The 20 most frequently words are ");
for(int i= 0; i<=19; i++){
System.out.print("Word "+ arreglo[i].Clave + " in " + arreglo[i].Valor + " times.");
}
}
}
2)
public class Par implements Comparable {
String Clave;
int Valor;
public int length;
public Par(String clave, int valor){
this.Clave = clave;
this.Valor = valor;
}
public int compareTo(Par p) {
if(this.Valor<p.Valor){
return 1;
}
else if(this.Valor==p.Valor){
return 0;
}
else{
return -1;
}
}
}
3)
public class ProcessText {
public void reader(Path r){
String name = clean(file.getName());
if(file.getName().equals(name + ".txt" || file.getName().equals(name + ".doc" ))){
try (Scanner sc = new Scanner(r)){
String doc = "";
while(sc.hasNextLine()){
String linea = (sc.nextLine());
doc = doc.concat(linea + "\n");
}
sc.close();
}
}
}
public static String clean(String s){
String r = "";
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (Character.isLetter(c)){
r = r + c;
}
}
return r.toLowerCase();
}
}
If this is all the code you have, your problem might be that your main method never creates a variable called "doc" or "file", but you use them both at the beginning of Client's main method.
It would be more helpful if you could share the compile time error, though, so I can't be sure that this is your problem.

Use File IO and make data shows in clear way

I try use file IO declare obj that I create for baseball team information, but I dont know why the arrayList save the same data again and again, I want each data save once in arraylist. thank you
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String fileName = "abc.txt"; //file name
// System.out.println("Please Enter The Source File Name:: ");
// fileName = in.nextLine();
ArrayList<Team> group = new ArrayList<Team>(); //use arrayList save data from obj
File file = new File(fileName); //open file
Scanner scan = new Scanner(file);
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
for (int i = 0; i < file.length(); i++) { //use split part to declear obj"Team"
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
// scan.close();
//try to close but shows error"Scanner closed"
}
for(int i =0; i < group.size(); i++) { //check arrayList work well, but fail
System.out.println(group.get(i).getName());
}
}
In your code, for loop inside while loop seems to make duplicated entries
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
**try this :**
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class SureshTemp
{
public static void main(String[] args) {
BufferedReader bf=null;
ArrayList al=new ArrayList();
try
{
String currentLine;
bf=new BufferedReader(new FileReader("D:\\abc.txt"));
while((currentLine=bf.readLine())!=null)
{
System.out.println(currentLine);
String str=currentLine;
String[] arr=str.split(",");
int n=Integer.parseInt(arr[3]);
int m=Integer.parseInt(arr[4]);
Team t=new Team(arr[0],arr[1], arr[2], n, m);
al.add(t);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if (bf != null)bf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for(int i =0; i < al.size(); i++){
System.out.println(al.get(i));
}
}
}
class Team
{
private String First;
private String next;
private String third;
private int won;
private int lost;
public Team(String F,String N,String T,int w,int l)
{
First=F;
next=N;
third=T;
won=w;
lost=l;
}
#Override
public String toString() {
return "Team [First=" + First + ", next=" + next + ", third=" + third
+ ", won=" + won + ", lost=" + lost + "]";
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public int getWon() {
return won;
}
public void setWon(int won) {
this.won = won;
}
public int getLost() {
return lost;
}
public void setLost(int lost) {
this.lost = lost;
}
}
try this :
while (scan.hasNext()) {
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4].trim()); // Use trim()to avoid NumberFormatException
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}

how to add multiple object on array list

I would like to add multiple objects to an ArrayList but I can't do it with my code. Here is the code I'm currently using. In the for loop, its adding the same object to the ArrayList 5 times. Why is this occurring?
import java.util.ArrayList;
import java.util.Scanner;
public class newBook {
public int no;
public String isim;
public newBook(int no ,String isim){
this.no = no;
this.isim = isim;
}
#Override
public String toString(){
return " no = " + this.no +", name = " + this.isim;
}
public static void main(String args[]){
Scanner klavye = new Scanner(System.in);
int kitapNo = klavye.nextInt();
String kitapName = klavye.next();
ArrayList<newBook> liste = new ArrayList<>();
for(int i=0 ; i<5 ; i++){
liste.add( new newBook(kitapNo,kitapName));
//System.out.println("Çıkmak için -1 giriniz ");
//int i = klavye.nextInt();
}
for (newBook liste1 : liste) {
System.out.println(liste1);
}
}
}
They are not the same object, they just have the same content. You need to read the input from klavye inside the loop too.

Sorting the User input in Java

I am beginner in Java. I need help to proceed my code. Thanks in advance.
Question: Given a unsorted list of 5 athletes nominated for the coaching class, provide a way for the coach to search for the athlete name and provide grades. Finally print the list of athletes’ names with their grade in the sorted order of their names. Search for the athlete with highest grade.
package student;
import java.util.Scanner;
public class Atheletes {
String name;
static String grade,grade1,grade2,grade3,grade4;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of athelete1 and grade");
grade1 = in.nextLine();
Scanner ino = new Scanner(System.in);
System.out.println("Enter the name of athelete2 and grade");
grade2 = ino.nextLine();
Scanner ine = new Scanner(System.in);
System.out.println("Enter the name of athelete3and grade");
grade3 = ine.nextLine();
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of athelete4 and grade");
grade4 = inp.nextLine();
}
}
I have simplified your code and added comments as necessary.
// number of Athletes you want
Athlete[] eAthlete = new Athlete[5];
// Name of each athlete
String[] names = { "ss", "aa", "bb", "cc", "xx" };
// On each iteration, the name of the Athlete
// and his/her grade is set,
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
At this point, the grades and names are assigned to each athlete,
Output
Before Sorting
ss 123
aa 65465
bb 4654
cc .0231
xx 23123
Now we need to sort these Athletes based on their names.
We could have designed our own Comparator but since, you are not allowed to use Collections.sort, we would use rather poor approach i.e bubble sorting,
String tempStr;
for (int t=0; t<eAthlete.length-1; t++)
{
for (int i= 0; i < eAthlete.length - t -1; i++)
{
if(eAthlete[i+1].getName().compareTo(eAthlete[i].getName())<0)
{
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i+1].getName());
eAthlete[i+1].setName(tempStr);
}
}
}
Printing the sorted athletes with their grades,
System.out.println("After Sorting");
for (Athelete s : eAthelete){
System.out.println(s.getName() + " " + s.getGrade());
}
Output:
After Sorting
aa 65465
bb 4654
cc .0231
ss 123
xx 23123
observe the names in above output.
here is your Athlete class,
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
Here is the complete code,
public class Main {
public static void main(String[] args) {
Athlete[] eAthlete = new Athlete[5];
String[] names = { "ss", "aa", "bb", "cc", "xx" };
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
String tempStr;
for (int t = 0; t < eAthlete.length - 1; t++) {
for (int i = 0; i < eAthlete.length - t - 1; i++) {
if (eAthlete[i + 1].getName().compareTo(eAthlete[i].getName()) < 0) {
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i + 1].getName());
eAthlete[i + 1].setName(tempStr);
}
}
}
System.out.println("After Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
}
}
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
public class Athletes {
private String name;
private String grade;
public Athletes(String name, String grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Athletes [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
List<Athletes> lijst = new ArrayList<Athletes>();
lijst.add(new Athletes("bbb", "Grade1"));
lijst.add(new Athletes("ccc", "Grade2"));
lijst.add(new Athletes("aaa", "Grade3"));
lijst.add(new Athletes("ddd", "Grade4"));
Collections.sort(lijst, new Comparator<Athletes>() {
#Override
public int compare(Athletes o1, Athletes o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Athletes athletes : lijst) {
System.out.println(athletes);
}
}
}
You may write your own comparator Class to sort the Athelete on basis of their names
public class AtheleteComparator implements Comparator
{
#override
public int compare(Atheletes first,Atheletes second)
{
return first.name.compareTo(second.name);
}
}
Then simply use
Collections.sort(List<Athelete>list,Your own Comparator's object)
To find out athelete with highest grade write another comparator which compares grades
then use
Collections.sort(arrayList,Comparator); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
Ok, since you can use arrays and for loops but not collections:
public class Sorter(){
private int[] grades = {7, 6, 4, 10, 8};
private String[] names = {"John", "Erik", "Bob", "Frank", "Judy"};
public static void main(String args[]) {
new Sorter();
}
public Sorter(){
int[] tempGrades = {0, 0, 0, 0, 0};
String[] tempNames = {"", "", "", "", ""};
for (int x = 0; x < tempGrades.length; x++) {
if (grades[x] < tempGrades[1]) {
tempGrades[0] = grades[x];
tempNames[0] = names[x];
} else if (grades[x] < tempGrades[2]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = names[x];
} else if (grades[x] < tempGrades[3]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = names[x];
} else if (grades[x] < tempGrades[4]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = names[x];
} else {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = tempGrades[4];
tempGrades[4] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = tempNames[4];
tempNames[4] = names[x];
}
}
grades = tempGrades;
names = tempNames;
for (int x = 0; x < grades.length; x++) {
System.out.println(tempNames[x] + " " + tempGrades[x]);
}
}
}
just for the future:
you can use an ArrayList<Athlete> where Athlete is a class that accepts (String name, int grade) as constructor paramaters and sorts athletes by grade by implementing its own comparator or you can use a LinkedHashMap<Integer, String> that sorts values by Key<Integer>.
Note: Class names with plural like Athletes are best used for Singleton classes that only implement static methods and variables. Always name classes by function (in this case sorting), AthleteSorter is also viable.

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}

Categories