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;
}
}
}
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 create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
I think this part may be the reason I'm getting the NullPointerException error, but I don't know what I'm missing. I have put my full code for the program below just in case there is something that is wrong with that that is giving me that error message.
//client class
public class Downsize
{
public static void main (String [] args)
{
System.out.print("Do you want to downsize the company? (Y/N): ");
String dummy = APIO.getString().toUpperCase();
while (dummy.equals("Y"))
{
Employee employee = new Employee();
System.out.print("Do you want to downsize the company? (Y/N):
dummy = APIO.getString().toUpperCase();
}
}
}
//object class
public class Employee
{
int numEmp;
int sprayer;
int winner;
boolean [] employees;
public Employee()
{
System.out.print("How many employees? (0 to end): ");
int numEmp = APIO.getInt();
System.out.print("Who gets the spray can first?: ");
int sprayer = APIO.getInt();
FillArray();
Selection();
Winner();
}
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
public void Selection()
{
System.out.println("EM="); //debugging method
for (boolean em: employees)
{
System.out.println(em);
}
int complete = numEmp;
while (complete > 1)
{
System.out.print("spraycan passed to #" + sprayer);
if ((sprayer + 1) > numEmp)
{
sprayer = 0;
}
while (employees[sprayer + 1] == false)
{
sprayer++;
if (sprayer >= numEmp)
{
sprayer = 0;
}
}
employees[sprayer + 1] = false;
System.out.print(" - sprays #" + (sprayer + 1) + "'s hair");
complete--;
sprayer++;
while (employees[sprayer] == false)
{
sprayer++;
if (sprayer > numEmp)
{
sprayer = 1;
}
}
}
}
public void Winner()
{
if (sprayer == 0)
{
sprayer = 1;
System.out.print("\nThe Winner is #" + sprayer);
System.out.print("\n");
}
}
}
//stack trace for the error message
java.lang.NullPointerException
at Employee.FillArray(Employee.java:22)
at Employee.<init>(Employee.java:14)
at Downsize.main(Downsize.java:9)
You must initialize the employees array. Once you read in the number of employees, do employees = new boolean[numEmp]; (after the line int numEmp = APIO.getInt();). Otherwise, it is null, so trying to access employees[i] throws a NullPointerException.
I see that you guys are beating around the bush in #mook's answer so let me just clarify so the OP can understand it well instead of guessing.
class Example {
int size;
boolean[] array;
void initArray() {
size = 5;
array = new boolean[size];
}
}
After declaring the size of the array and its type, you need to initialize the array. In the above example array holds 5 booleans.
If instead you write
class Example {
int size;
boolean[] array = new boolean[size];;
void initArray() {
size = 5;
}
}
Then since int is set to 0 by default, the size of array will be 0 even if you change the variable you used to declare the size later in the code. This will give you an error since you will iterate up to 5.
#mook's answer is correct.
I have written a program which takes the words the user have entered, with a button press, and puts them in an ArrayList. There is also another text field where the user can enter a letter or word, for which the user can search for in the ArrayList with another button press. I'm using a sequential search algorithm to accomplish this, but it does not work as I expect it to; If the searched word is found, the search function should return, and print out in a textArea that the word was found and where in the array it was found. This works, but only for the first search. If the word is not found, the function should print out that the word was not found. This works as I want it to.
The problem is that after I searched for one word, and it displays where in the ArrayList this can be found, nothing happens when I press the button after that, whether the entered letter/word is in the array or not. It's like the string that the text gets stored isn't changing. I don't understand why... Here below is the custom Class of the search function and then my Main class:
public class Search {
static private int i;
static String index;
static boolean found = false;
public static String sequencial (ArrayList<String> list, String user) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
index = "The word " + user + " exist on the place " + i + " in the Arraylist";
found = true;
}
}
if (!found) {
index = "The word " + user + " could not be found";
}
return index;
}
My Main class:
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> s = new ArrayList<String>();
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtaOutput.setText("");
String word = txtfAdd.getText();
list.add(word);
for (int i = 0; i < list.size(); i++) {
txtaOutput.append("" + list.get(i) + "\n");
}
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String user = txtfSearch.getText();
txtaOutput.setText("");
String index = Search.sequencial(list, user);
txtaOutput.setText("" + index);
}
Any help is appreciated!
The problem is that you declared your found variable as static. When your first word is found, it is set to true, and nothing ever sets it back to false. Instead of making it a static variable, declare it as a local variable inside your sequencial (it's spelled sequential, by the way) function, just before the for-loop.
In fact, all the variables you've declared as static should be made local. Declaring static variables is never a good idea.
As said by other users:
There is the List#indexOf(Object) method. You should use that instead of reinventing the wheel (unless you need to, and in that case you might have a look at the ArrayList implementation). There are also other collections, like HashSet which are more apropiate for looking up, but i guess that is another history.
The scope and the names of the variables (i, index, found) is error-prone. Do other methods or even classes need to have access to those variables? If you need to keep those variables, you might want to choose a visibility (public,protected,private). "index" is a misleading choice of a name for a message.
This would be an slightly simplified/corrected version of your code:
// Ommit those unneeded static variables
public static String sequencial (ArrayList<String> list, String user) {
int indexFound = list.indexOf(user);
if (user >= 0) {
return "The word " + user + " exist on the place " + indexFound + " in the Arraylist";
} else {
return "The word " + user + " could not be found";
}
}
...
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String user = txtfSearch.getText();
// txtaOutput.setText("");
String seqMessage = sequencial(list, user);
txtaOutput.setText(seqMessage);
}
We use the static properties when you would like to use the constants. You should not use the static properties here. The problem will happen when your found property is changed the first time, it will not be changed again. And from that time, it will always be true. Similar with index property. Here is the code you can fix this:
public class Search {
public static SearchResult sequencial (ArrayList<String> list, String user) {
SearchResult result = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
String index = "The word " + user + " exist on the place " + i + " in the Arraylist";
boolean found = true;
result = new SearchResult(index, found);
break;
}
}
if (result == null) {
String index = "The word " + user + " could not be found";
result = new SearchResult(index);
}
return result;
}
//sample inner class
static class SearchResult {
private String index;
private boolean found;
public SearchResult(String index) {
this.index = index;
}
public SearchResult(String index, boolean found) {
this.index = index;
this.found = found;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
}
}
public class SequencialSearcher {
public static int SequencialSearchInt(int[] inputArray, int key)
{
for(int i=0; i < inputArray.length ; i++)
{
if(inputArray[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchString(String[] array, String key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchFloat(double[] array, double key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static void main (String args[])
{
//select the type of the elements of search
//1 if integers
//2 if float
//3 if string
int x = 3;
int[] array1 = {9, 0, 10, 8, 5, 4, 6, 2, 3};
double[] array2 = {9.0, 0.0, 10.0, 8.0, 5.0, 4.0, 6.0, 2.0, 3.0};
String[] array3 = {"aa","hey", "hello"};
if(x == 1){
//enter the integer you want to search for here below
int requiredValue = 5;
int result = SequencialSearchInt(array1, requiredValue);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue+" not found");
}
}
else if(x == 2)
{
//enter the double you want to search for here below
double requiredValue1 = 5.0;
int result = SequencialSearchFloat(array2, requiredValue1);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue1+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue1+" not found");
}
}
else if(x == 3){
//enter the string you want to search for here below
String requiredValue2 = "hey";
int result = SequencialSearchString(array3, requiredValue2);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue2+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue2+" not found");
}
}
else{
System.out.println("Error. Please select 1,2 and 3 only");
}
}
}
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).