Arrays with mutliple elements in java and other Issue - java

Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class

You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.

'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.

Related

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Descending order by using for statement in java

There is a list of 200 students names and exam results.
My task is: "Create a constructor method for this list and put them in descending order with for statement".
I've done the first part. I can print out the list also. But I have no idea how to put them in descending order using for statement. Can anyone show me how to do that?
Current code:
package training;
public class ExamResult {
String studentName;
String examName;
int points;
String date;
ExamResult(String studentName, String examName, String date,int points) {
this.studentName=studentName;
this.examName=examName;
this.points=points;
this.date=date;
}
public void display() {
System.out.println(studentName + " " + examName + " " + date + " " + points);
}
}
package training;
public class DisplayExamResults {
public static void main (String args[]) {
ExamResult one=new ExamResult("Ryan Pena","Sociology","21/06/2016",16);
ExamResult two=new ExamResult("Portia Hamilton","Sociology","21/06/2016",34);
ExamResult three=new ExamResult("Ryan Pena","Sociology","21/06/2016",35);
one.display();
two.display();
three.display();
}
}
So, Daniel! This is going to be long because you are new to Java and I will try to explain everything. You can always read more about a lot of things here but I will explain just enough for this problem.
When you want to sort objects of a class, in your case, class ExamResult, you cannot just use a for loop on one of the fields and finish sorting. In order to achieve your desired sorting, you will need to use an interface called Comparable. This interface lets you write your own sorting criteria based on the structure of your class.
We will proceed step by step.
Step 1: Implement the Comparable interface in the ExamResult class
Since you want to sort objects of the ExamResult class, this is where you will implement the interface. By that, we mean, you will write how you want to sort your objects. We want to sort based on the student names. And for sorting, we will need to compare objects to see which one is greater than the other.
Here, we will use a term called overriding which basically means that we will override the comparison function which was declared in the Comparable interface.
Our definition below takes as input an object of the class ExamResult and compares its student name with that of the current object - this. On comparison, it returns an integer:
0, if the names are equal
>0, if the other object's student name is greater than the current one
<0, if the other object's student name is lesser than the current one
package training;
public class ExamResult implements Comparable<ExamResult> {
/* your previous code remains here as is*/
// this function returns the name of the student
public String getStudentName() { return studentName; }
#Override
// write your sorting criteria
public int compareTo(ExamResult other) {
String name1 = this.getStudentName();
String name2 = other.getStudentName();
return name1.compareTo(name2);
}
}
Step 2: Construct a list of ExamResult objects in DisplayExamResults class
Now that we have finished defining how to compare objects, we need a list of those objects on which we will run the for loop and perform the comparison.
We can do that in the DisplayExamResults class like so:
// Create a list of results on which you will run your for loop
List<ExamResult> resultList = new ArrayList<>();
resultList.add(one);
resultList.add(two);
resultList.add(three);
Here, the List interface lets you define a list of objects of any user defined class like yours. So you create a list and add the ExamResult objects to it.
Step 3: Sort using the for loop
This is the final step, where you perform the actual sorting in the DisplayExamResults class. We will first sort in ascending order and then reverse the list.
You start with a left (i) and a right (j) pointer. i is set to 0 because it starts at the beginning of the list and j is set at the end of the list.
As you keep comparing, if the object on the left is smaller than the one on the right, you just move on, i.e. increment i. Similarly, if the object on the right is greater than that on the left, just move on by decrementing j.
But, if the order is not like that, then you swap them. Which is what we do in the if statement. You can see that we are using the compareTo() function that we had defined above.
// Loop over that list to sort the objects
for (int i = 0; i < resultList.size(); i++) {
for (int j = resultList.size() - 1; j > i; j--) {
if (resultList.get(i).compareTo(resultList.get(j)) > 0) {
ExamResult temp = resultList.get(i);
resultList.set(i, resultList.get(j));
resultList.set(j, temp);
}
}
}
// For descending order
Collections.reverse(resultList);
// Display the results after sorting is over
for (ExamResult r : resultList) {
r.display();
}
Phew! Now, we put all that code together to get the following two files.
package training;
public class ExamResult implements Comparable<ExamResult> {
String studentName;
String examName;
int points;
String date;
ExamResult(String studentName, String examName, String date,int points) {
this.studentName=studentName;
this.examName=examName;
this.points=points;
this.date=date;
}
public void display() {
System.out.println(studentName + " " + examName + " " + date + " " + points);
}
// this function returns the name of the student
public String getStudentName() { return studentName; }
#Override
// write your sorting criteria
public int compareTo(ExamResult other) {
String name1 = this.getStudentName();
String name2 = other.getStudentName();
return name1.compareTo(name2);
}
}
And
package training;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DisplayExamResults {
public static void main (String args[]) {
ExamResult one = new ExamResult("Ryan Pena","Sociology","21/06/2016",16);
ExamResult two = new ExamResult("Portia Hamilton","Sociology","21/06/2016",34);
ExamResult three = new ExamResult("Ryan Pena","Sociology","21/06/2016",35);
one.display();
two.display();
three.display();
System.out.println("\n");
// Create a list of results on which you will run your for loop
List<ExamResult> resultList = new ArrayList<>();
resultList.add(one);
resultList.add(two);
resultList.add(three);
// Loop over that list to sort the objects
for (int i = 0; i < resultList.size(); i++) {
for (int j = resultList.size() - 1; j > i; j--) {
if (resultList.get(i).compareTo(resultList.get(j)) > 0) {
ExamResult temp = resultList.get(i);
resultList.set(i, resultList.get(j));
resultList.set(j, temp);
}
}
}
// For descending order
Collections.reverse(resultList);
// Display the results after sorting is over
for (ExamResult r : resultList) {
r.display();
}
}
}
I tried to explain the bits in there. Please read more and understand better. Hope it helps.
If the names are as a String Array or a List:
Using standard Java libraries:
String[] students = {"Aaron", "Jonas", "Bob", "Karl"};
Arrays.sort(students);
List<String> temp = new ArrayList<>(Arrays.asList(students));
Collections.reverse(temp);
temp.toArray(students);
OR
Using Bubblesort and chars to compare the strings:
String[] students = {"Aaron", "Jonas", "Bob", "Karl"};
char[] temp1;
char[] temp2;
int length;
for(int i = 0; i < students.length; i++){
temp1 = students[i].toLowerCase().toCharArray();
for(int n = i+1; n < students.length; n++){
temp2 = students[n].toLowerCase().toCharArray();
if(temp1.length > temp2.length)
length = temp2.length;
else
length = temp1.length;
for(int c = 0; c < length; c++){
if(temp1[c] < temp2[c]){
String temp = students[i];
students[i] = students[n];
students[n] = temp;
temp1 = students[i].toLowerCase().toCharArray();
break;
}
else if(temp1[c] > temp2[c])
break;
}
}
}

How to sort objects of an array in ascending order?

I need to sort the marks in ascending order. It shows me the error: "Incompatible types".
static void sortimi(Studenti[] std ){
int perk=0;
for (int i=0; i<std.length; i++) {
for(int j=1; j<std.length - i; j++) {
if(std[j-1] > std[j]){ // Error: Bad operand types for binary operator
perk=std[j-1]; // Error: Incompatible types
std[j]=perk; // Error: Incompatible types
}
}
}
public class Studentat {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Studenti[] std= new Studenti[3];
for(int i=0; i<std.length;i++){
std[i]= new Studenti();
}
for(int i = 0; i < std.length; i++){
System.out.println(std.toString());
}
}
public class Studenti {
private String name;
private int mark;
public Studenti(){
Scanner s = new Scanner(System.in);
System.out.print("Write student's name:" + " ");
this.name = s.nextLine();
System.out.print("Write students' mark:" + " ");
this.mark = s.nextInt();
if(mark<5 || mark>10){
mark = 0;
System.out.println("The given mark is wrong");
}
}
static void sortimi(Studenti[] std ){
int perk=0;
for (int i=0; i<std.length; i++) {
for(int j=1; j<std.length - i; j++) {
if(std[j-1] > std[j]){ // Error: Bad operand types for binary operator
perk=std[j-1]; // Error: Incompatible types
std[j]=perk; // Error: Incompatible types
}
}
}
}
First, in sortimi(Studenti[] std), just declare perk to be of type Studenti instead of int:
Studenti perk = null;
Also, you seem to have declared the method sortimi(Studenti[] std) twice. You'll have to get rid of one of them.
Finally, you can't compare instances of Studenti using the > operator. You'll have to define some sort of comparison method or else sort on a field. For instance:
public class Studenti {
...
public boolean precedes(Studenti other) {
// logic for deciding order for students
}
}
Alternatively (and preferably, in my opinion), you can declare one or more static nested classes of Studenti that implements the Comparator<Studenti> interface. Then to sort the array you can just call Arrays.sort() and pass an instance of the appropriate comparator class. The advantage of this approach is that you can have several classes that sort on different criteria (e.g., student name only vs. by mark and then by student name). The reason I recommend static nested class is that your Studenti class provides no mechanism for outside classes to access the field values. If you made the fields final public instead of private or if you provided accessor methods, you could make the comparator classes separate, top-level classes and keep the Studenti class fairly streamlined.
To sort an item the item should be comparable. Here you can do it two ways.
So we need Student class to be Comparable
public class Studenti extends Comparable<Studenti> {
private String name;
private int mark;
public Studenti() {
Scanner s = new Scanner(System.in);
System.out.print("Write student's name:" + " ");
this.name = s.nextLine();
System.out.print("Write students' mark:" + " ");
this.mark = s.nextInt();
if (mark < 5 || mark > 10) {
mark = 0;
System.out.println("The given mark is wrong");
}
}
public int getMark() {
return mark;
}
public void setMark(int newMark) {
this.mark = newMark;
}
#Override
public int compareTo(Studenti o) {
return o.getMark() - this.mark; //Change this statement for reversing the sort order.
}
}
now you can do
Arrays.sort(studentsArray);
Refer this for more details
https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

How do I access the itemPrice part of this array?

So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}

Sorting a class array in Java?

I'm making a number guessing game for a school project in Java, which I'm extremely bad at. I've got everything to work with classes and the guessing part, but now I'm going to create a top players list and sort it and I have no idea how.
This is the code I use for guessing and creating objects of the player.
public static void spela() {
int nummer= ((int) (1+Math.random()*100));
Scanner input = new Scanner(System.in);
Scanner s_input = new Scanner(System.in);
boolean ratt = false;
int forsok = 1;
int gissning;
String namn;
while(ratt==false) {
System.out.println("Gissa nummer: ");
gissning = input.nextInt();
if(gissning == nummer) {
System.out.println("Grattis du gissade rätt! Tog: " + forsok + " försök att gissa rätt!");
System.out.println("Skriv in namn: ");
namn = s_input.nextLine();
for(int i=0;i<cr;i++) {
if(namn.equals(allaspelare[i].namn)) {
allaspelare[i].setpoang(forsok);
ratt=true;
menu();
}
}
allaspelare[cr] = new spelare(namn);
allaspelare[cr].setpoang(forsok);
cr++;
ratt=true;
menu();
}
if(gissning > nummer) {
System.out.println("Du gissade: " + gissning + " och det var för mycket!");
}
if(gissning < nummer) {
System.out.println("Du gissade: " + gissning + " och det var för lite!");
}
forsok++;
}
}
this is the "spelare" class:
public class spelare {
int[] poang = new int[100];
int antal;
String namn;
public spelare(String innamn) {
namn = innamn;
}
public void setpoang(int inpoang) {
poang[antal] = inpoang;
antal++;
}
}
as you see one player can have multiple scores so that's the problem I can't get it right in my mind how I'm going to sort it so the output if I wan't to get out the score chart will come like:
testplayer1: 9
testplayer2: 11
testplayer3: 34
So basically I need help to code a method that goes through the class and sort it and output it as above! Any help/sources is extremely appreciated!
And commented code would be extremely appreciated so I can learn!
EDIT:
I've been searching for hours, and the only thing that I found was this:
public static void sortera(int[] lista, int plats) {
int i;
if (lista.length < 2) return;
int temp;
for(int n=1; n<lista.length; n++) {
temp=lista[n];
i = n - 1;
while(i >=0 && lista[i] > temp) {
lista[i+1] = lista[i];
}
lista[i+1] = temp;
}
allaspelare[plats].poang = lista;
}
And this is how I called it:
case 5:
sortera(allaspelare[0].poang, 0);
break;
but this doesn't do anything..
The structure you use is simply bad. Instead you should use pairs of names and scores. This way multiple scorepairs with the same name exist, but you can easily sort them.
public class Score implements Comparable<Score>{
private int score;
private String name;
public Score(String name , int score){
this.score = score;
this.name = name;
}
//getters and setters as required
public int compareTo(Score s){
return score - s.score;
}
}
This aswell allows you to directly compare Scoreobjects to eachother. This way a list of Score objects can easily be sorted via Collections.sort(someList).

Categories

Resources