I cannot figure out how to format the code for my if-statements. Typically, I would take a string input from the user and use .equals, however the object I am required to use makes that impossible. Whenever I print the contents of the array, I get references. I want to get a user input stored to be stored in the array and printed in a later line of code.
Question: If possible, how do I get a scanner input to be assigned to a "Team" and referenced for comparison in the if-statements? How should I go about assigning these values?
Here is the code I was given
public class Team implements Comparable<Team> {
public String toString(String team, int wins) {
String winningStatement = team + ": " + wins;
return winningStatement;
}
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
Here is my attempt at using an ArrayList
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
Thank you for the assistance
Judging only by the intent of your example... it appears that this is what you are trying to achieve. As stated though, your question of how ArrayList objects relate to overloaded constructors does not really make sense
public class Team {
// Data fields
private String name;
private int winCount;
public Team() {
name = "Sooners";
winCount = 1;
}
public Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
public String toString(String team, int wins) {
return team + ": " + wins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinCount() {
return winCount;
}
public void setWinCount(int winCount) {
this.winCount = winCount;
}
void incrementWinCount() {
winCount++;
}
}
void runSystem() {
List<Team> teams = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int cycles = 0;
System.out.println("Welcome to the Advanced Sportsball Tracker!");
System.out.println("Which team just won? (x to exit)");
String name = scnr.next();
while (!"x".equals(name)) {
final String teamName = name;
Team team = teams.stream().filter(t -> teamName.equals(t.getName())).findAny().orElse(null);
if (team == null) {
team = new Team(teamName, 1);
teams.add(team);
}
else {
team.incrementWinCount();
}
cycles++;
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
}
}
Related
I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am building the object with the classical Nim game, and there are some methods dealing with the player data. I bumped into this problem when testing my code, and couldn't figure it out.
This problem appeared when I add a player in an array, removing it after. Then, adding a player again. It showed: Index 1 out of bounds for length 1. What I've tried is to filter the null position when I remove the player data.
Any help is highly appreciated. And thank you all for the patience and time solving it!
The code is a little bit longer, but related.
Here is the related code from class Nimsys, main method.
public static void addPlayer(String [] name) {
if (name != null && name.length == 3) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exists.\n");// Test if player has been created
return;
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
return;
}
System.out.println("Not Valid! Please enter again!");
}
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
//Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
addPlayer(name);
}
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
Here is part of my NimPlayer class:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
NimPlayer.playerList = newplayerList;
1. Replace
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
with
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.isEmpty()) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.nextLine();
if (commandin.equalsIgnoreCase("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
NimPlayer.removePlayer(playerList[i]);
}
System.out.println("Removed all the players\n");
}
} else {
searchAndRemovePlayer(user);
}
}
2. Change the following methods as given below:
public static void searchAndRemovePlayer(String user) {
NimPlayer[] playerList = NimPlayer.getPlayerList();
for (int i = 0; i < playerList.length; i++) {
String userName = playerList[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.removePlayer(playerList[i]);
System.out.println("The player, " + user + " removed successfully!");
return;
}
}
System.out.println("The player, " + user + " does not exist.\n");
}
public static NimPlayer [] getPlayer() {
return Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
}
2. Instead of exposing the playerList to be set from outside, you should remove its public setter and create public static void removePlayer similar to public static void createPlayer as follows:
public static void removePlayer(NimPlayer player) {
int i;
for (i = 0; i < playerList.length; i++) {
if (playerList[i] != null && playerList[i].getUserName().equals(player.getUserName())) {
break;
}
}
for (int j = i; j < playerList.length - 1; j++) {
playerList[j] = playerList[j + 1];
}
counter--;
}
Important note: Never put setting operation within getter, the way you have done in your method, getPlayer().
You need to use Iterator and call remove() on iterator instead of assigning to null.
Duplicate from: Removing items from a list
You shouldn't do a "playerList[i] = null;" for removing a player. Use an ArrayList instead and use the ArrayList's .remove method to remove a player. don't keep track of counter variables.
My assignment is I have to manage a soccer league.There is a soccer league (text file) that I have to import into the program.Each line of the imported file displays the outcome of a single game:the name of two teams together with the scores like
Peter 4 Tiger 3
Sky 2 Peter 0
Tiger 1 Sky 2
I have to write the program to read this text file and displays the output of team records like
Team Wins Losses
Peter 1 1
Tiger 0 2
Sky 2 0
I don't understand how to read through the lines and calculate the wins and losses associated with each team/String.
import java.util.*;
import java.io.*;
public class SoccerLeagueStandings
{
public static void main(String[] args) throws IOException
{
File inFile = new File("LeagueScore.txt");
if(! inFile.exists())
{
System.out.println("Error could not open the file");
return;
}
String Panthers="Panthers";
String Tigers = "Tigers";
String Sky = "Sky";
Scanner input = new Scanner (inFile);
int PW=0;
int PL=0;
int TW =0;
int TL = 0;
int SW=0;
int SL=0;
while (input.hasNextLine())
{
String firstTeam=input.next();
input.nextInt();
int firstScore=input.nextInt();
String secondTeam=input.next();
input.nextInt();
int secondScore = input.nextInt();
if (firstScore>secondScore)
{
if (firstTeam.equals(Panthers))
{
PW+=1;
}
if (firstTeam.equals(Tigers))
{
TW+=1;
}
if (firstTeam.equals(Sky))
{
SW+=1;
}
}
}
}
}
The main challenge in this problem is to keep track of the wins and losses of each team.
So i suggest to create a class called Team which holds: name, winsCount, lossCount. This class represents a single team along with its wins and loss count.
Create an arrayList of Team and fill it using the file content.
So your algorithm would be as the following:
Parse the file line by line using Scanner.
Split each line by space in order to get the teams and their scores.
Compare the scores of the teams.
Add the winner team to the ArrayList OR increment its winsCount if already exist.
Do the same for the loser team.
Below is a non-tested sample code:
Following is the Team class:
public class Team {
private String name;
private int winsCount;
private int lossCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinsCount() {
return winsCount;
}
public void setWinsCount(int winsCount) {
this.winsCount = winsCount;
}
public int getLossCount() {
return lossCount;
}
public void setLossCount(int lossCount) {
this.lossCount = lossCount;
}
}
Below is how to fill the arraylist from the input file:
private void generateWinsLossesFromInput(String filePath)
{
Scanner input = new Scanner(filePath);
List<Team> teams = new ArrayList<Team>();
while(input.hasNext())
{
String match = input.next();
// Split the line and get teams and their scores.
String[] splittedMatch = match.split("\\s+");
String firstTeam = splittedMatch[0];
int firstTeamScore = Integer.parseInt(splittedMatch[1]);
String secondTeam = splittedMatch[2];
int secondTeamScore = Integer.parseInt(splittedMatch[3]);
if(firstTeamScore > secondTeamScore)
{
addWinner(firstTeam, teams);
addLoser(secondTeam, teams);
}
else
{
if(secondTeamScore > firstTeamScore)
{
addWinner(secondTeam,teams);
addLoser(firstTeam, teams);
}
}
}
}
private void addWinner(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its winsCount
t.setWinsCount(t.getWinsCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found, So add it as new team to the list.
Team t = new Team();
t.setName(team);
t.setWinsCount(1);
t.setLossCount(0);
teams.add(t);
}
}
private void addLoser(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its loss count.
t.setLossCount(t.getLossCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found , then add new team to the list
Team t = new Team();
t.setName(team);
t.setWinsCount(0);
t.setLossCount(1);
teams.add(t);
}
}
At the end, you would be able to iterate over the array list and print out each team along with its Wins and loss counts.
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.
I am trying to output the names and corresponding scores in descending order. Having an array of strings and another array of integers, I am trying to relate the two arrays. I used Arrays.sort and tries to get the indices. The indices is then to be used to arrange the names in similar location as the corresponding scores. I have this code but I get run time error saying unfortunately, your app has stopped. Can anyone please help me on what to be done to achieve my goal here? Thank you so much!
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Arrays.sort(score);
int index_array[] = new int[4];
int m = 0;
for(m = 0; m <4; m++){
index_array[m]=Arrays.binarySearch(score ,score[m]);
l = index_array[0];
}
for(int i = 0; i<4; i++){
if(l == score[i]){
j = i;
}
}
String name = names[m];
show.setText(name + " " + Integer.toString(l));
Create Player model which holds player's name and score and then use Comparator to sort players by score.
Player model:
class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String toString() {
return "name=" + name + "; score=" + score;
}
}
Comparator:
class PlayerComparator implements Comparator<Player> {
public int compare(Player p1, Player p2) {
return p1.getScore() < p2.getScore() ? -1
: p1.getScore() > p2.getScore() ? 1 : 0;
}
}
And an example of usage:
public class PlayerTest {
public static void main(String[] args) {
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Player[] players = new Player[names.length];
for(int i = 0; i < names.length; i++) {
players[i] = new Player(names[i], score[i]);
}
Arrays.sort(players, new PlayerComparator());
}
}
you need to associate the score and the user name. Currently, you are associating them by array index. when you sort the scores, the indices of the scores will change.
Try something like this:
class Score implements Comparable<Score>
{
int score;
String player;
public Score(int theScore, String thePlayer)
{
score = theScore;
player = thePlayer;
}
public int compareTo(Score)
{
... compare based on the int score value ...
}
... getters. setters optional ...
}
List<Score> scoreList = new ArrayList<Score>();
... fill scoreList with Score objects. ...
Collections.sort(scoreList);
This is a design smell. You shouldn't have two parallel arrays. Instead, you should have a single array of Player objects, where each Player would have a name and a score.
Storing the arra of players by name or by score would then be extremely simple.
Java is an OO language. Use objects.
public class Player
private final String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
...
Player[] players = new Player[4];
players[0] = new Player("player1", 10);
...