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).
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
I want to sort students by their roll numbers. I know how to sort an arraylist of integers using merge sort, but sorting an ArrayList of type Student is different.
my Student class contains the following properties:
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
}
I've seen people use Comparators to sort ArrayLists of object's properties. However, they use it for built-in sorting like the following line (which is straightforward):
Collections.sort(Database.arrayList, new CustomComparator());
However, I want to use my mergesort functions that I wrote in my Student class. But I still don't understand how am I going to pass the property 'rollNum' into the mergesort function and how are other properties in the ArrayList are going to be moved accordingly? I've never seen this anywhere in Google.
Here is my full code:
package student;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;
public class Main
{
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
public String getName()
{
return name;
}
public int getRollNum()
{
return rollNum;
}
public int getWebMark()
{
return WebMark;
}
public int getDSMark()
{
return dsMark;
}
public int getDMMark()
{
return dmMark;
}
public static void addStudent(ArrayList<Student> studentArray)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Name: ");
String name = input.next();
System.out.println("Enter Roll Number");
int rollNum = input.nextInt();
System.out.println("Enter Web Mark:");
int webMark = input.nextInt();
System.out.println("Enter Data Structure Mark:");
int DSMark = input.nextInt();
System.out.println("Enter Discrete Math Mark:");
int DMMark = input.nextInt();
//create this student profile in array
Student newStudent = new Student(name,rollNum,webMark,DSMark,DMMark);
studentArray.add(newStudent);
}
public static void findStudent(int rollNum, ArrayList<Student> studentArr)
{
for(int i = 0; i < studentArr.size(); i++)
{
if(studentArr.get(i).getRollNum()==rollNum)
{
System.out.println("Roll Number: " + studentArr.get(i).getRollNum() +
", Name: " + studentArr.get(i).getName() +
", Web Grade: " + studentArr.get(i).getWebMark() +
", Data Structure Grade: " + studentArr.get(i).getDSMark() +
", Discrete Math Grade: " + studentArr.get(i).getDMMark());
}
else
{
System.out.println("Couldn't find student.");
}
}
}
public static void deleteStudent(ArrayList<Student> studentArr)
{
System.out.println("Enter Student Roll Number: ");
Scanner input = new Scanner(System.in);
int rollNum = input.nextInt();
for(int counter = 0; counter < studentArr.size(); counter++)
{
if(studentArr.get(counter).getRollNum() == rollNum)
{
studentArr.remove(counter);
}
}
}
public String toString()
{
return name + " " + rollNum + " " + WebMark + " " + dsMark + " " + dmMark;
}
public static double avg(ArrayList<Student> studentArr)
{
double[] avgArr = new double[studentArr.size()];
double max = 0.0;
for(int counter = 0; counter < studentArr.size(); counter++)
{
avgArr[counter] = (studentArr.get(counter).getWebMark() +
studentArr.get(counter).getDSMark() + studentArr.get(counter).getDMMark())/(3);
if(avgArr[counter] > max)
{
max = avgArr[counter];
}
}
return max;
}
public int compareTo(Student studCompare)
{
int compareRollNum = ((Student) studCompare).getRollNum();
//ascending order
return this.rollNum - compareRollNum;
}
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuNameComparator = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
String StudentName1 = s1.getName().toUpperCase();
String StudentName2 = s2.getName().toUpperCase();
//ascending order
return StudentName1.compareTo(StudentName2);
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuRollno = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
int rollno1 = s1.getRollNum();
int rollno2 = s2.getRollNum();
//ascending order
return rollno1-rollno2;
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
{
// exception
if (m==null) throw new NoSuchElementException("List is null");
// base case
if (m.size() <= 1) return m;
// make lists
List<T> left = new ArrayList<>();
List<T> right = new ArrayList<>();
// get middle
int middle = m.size()/2;
// fill left list
for (int i = 0; i < middle; i++)
{
if (m.get(i)!=null) left.add(m.get(i));
}
// fill right list
for (int i = middle; i < m.size(); i++)
{
if (m.get(i)!=null) right.add(m.get(i));
}
// recurse
left = mergeSort(left);
right = mergeSort(right);
// merge
return merge(left,right);
}
private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
{
List<T> result = new ArrayList<>();
// merge
while (!left.isEmpty() && !right.isEmpty())
{
if (left.get(0).compareTo(right.get(0)) <= 0)
{
result.add(left.remove(0));
}
else
{
result.add(right.remove(0));
}
}
// cleanup leftovers
while (!left.isEmpty())
{
result.add(left.remove(0));
}
while (!right.isEmpty())
{
result.add(right.remove(0));
}
return result;
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userChoice = 0;
int userChoice2 = 0;
ArrayList<Student> studentArr = new ArrayList<Student>(); //array size is 6
System.out.println("1- Merge Sort");
System.out.println("2- Shell Sort");
System.out.println("3- Quit");
userChoice2 = input.nextInt();
if (userChoice2 == 1 || userChoice2 == 2)
{
do {
System.out.println("1- Add a New Record");
System.out.println("2- Sort by Student Name");
System.out.println("3- Sort by Roll Number");
System.out.println("4- Delete a Student Specific Record");
System.out.println("5- Display a Student Specific Record");
System.out.println("6- Search");
System.out.println("7- Display the Highest Average");
System.out.println("8- Print"); //print the array size, sort time, and number of comparisons to the screen.
System.out.println("9- Quit");
System.out.println("Select your Option: \n");
userChoice = input.nextInt();
switch (userChoice) {
case 1:
Student.addStudent(studentArr);
break;
case 2:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 3:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 4:
Student.deleteStudent(studentArr);
break;
case 5:
System.out.println("Enter Student Roll Number: ");
int rollNum_ = input.nextInt();
Student.findStudent(rollNum_, studentArr);
break;
case 6:
case 7:
double highestAvg = Student.avg(studentArr);
System.out.println("Highest Average is: " + highestAvg);
break;
case 8:
System.out.println("Printing students...");
System.out.print(studentArr);
System.out.println("\n");
break;
case 9:
}
} while (userChoice != 9);
}
else
{
return;
}
input.close();
}
}
Your Student is already Comparable and it already compares to other Student instances using rollNum field, so the current implementation using compareTo() should already sort on that field.
But if you want to sort using a different ordering, you could write a Comparator and change your sorting method like so:
private static <T> List<T> merge(List<T> left, List<T> right, Comparator<? super T> comparator) {
.. use comparator.compare(a, b) instead of a.compareTo(b)
}
Here, you don't need to restrict T with Comparable.
in order to sort anything , the object must be comparable by somewhat. In java, there are 2 ways to do it for objects (like student):
Comparable and Comparator.
That being said, your object must implement Comparable interface and then write implementation of the necessary method compareTo where you list how you want then to compare to each other.
Another way is to implement Comparator interface and write implementation for compare method.
Once that is done, you can sort the collection with Collection.sort ..... method.
i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}
I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}
Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}
OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)