Removing position from HashMap - java

I'm working on a something like music player. I'm building playlist on HashMap, I have a problem with deleting specific setlist(case 5). It works but when I delete position in the middle of the list case 1 (showing all playlists) no longer works because I have empty space (1,2,3,deleted,5,6....). Now how do I make those positions after deleted one decrease index by one? Looks like x-- doesn't solve my problem. I hope you understand my problem, here is the code, if you need me to translate anything to English just ask. Thanks for help!
package PLAYLIST2;
import java.util.HashMap;
import java.util.Scanner;
public class Odtwarzacz {
// String lista;
// Odtwarzacz(Playlist) {
// lista = b;
// }
public static void main(String[] args) {
int nr;
int koniec = 0;
String nazwa11;
int x = 0;
HashMap<Integer, Playlist> Playlista = new HashMap<Integer, Playlist>();
Playlista.put(x, new Playlist("Rock"));
x++;
Playlista.get(0).dodajUtwor("Stockholm Syndrome", "Muse", 2004);
Playlista.get(0).dodajUtwor("Absolution", "Muse", 2004);
Playlista.put(x, new Playlist("Pop"));
x++;
Scanner odczyt = new Scanner(System.in);
// TODO Auto-generated method stub
while (koniec == 0) {
System.out.println("_________________________");
System.out.println("1.Wyświetl listę playlist");
System.out.println("2.Dodaj playlistę");
System.out.println("3.Wyświetl playlistę");
System.out.println("4.Posortuj playlistę");
System.out.println("5.Usuń playlistę");
nr = odczyt.nextInt();
switch (nr) {
case 1: {
System.out.println("Lista playlist: ");
for (int i = 0; i < x; i++) {
System.out.println(i + ". " + Playlista.get(i).Nazwa());
}
break;
}
case 2: {
System.out.print("Podaj nazwę nowej playlisty: ");
nazwa11 = odczyt.next();
Playlista.put(x, new Playlist(nazwa11));
System.out.println("Dodano playlistę: "
+ Playlista.get(x).Nazwa());
x++;
break;
}
case 3: {
System.out.print("Podaj numer playlisty:");
nr = odczyt.nextInt();
Playlista.get(nr).wyswietlListe();
break;
}
case 4: {
System.out.print("Podaj numer playlisty:");
nr = odczyt.nextInt();
Playlista.get(nr).sortuj();
break;
}
case 5: {
System.out.print("Podaj numer playlisty:");
nr = odczyt.nextInt();
System.out.println("Skasowano playlistę: "
+ Playlista.get(nr).Nazwa());
Playlista.remove(nr);
x--;
break;
}
}
}
}
}

You do not seem to need a HashMap.
A HashMap is just a key-value store that has no order.
In your case, a List seems like a better choice. It comes with an order since it is the main point of it.
You can specifically use a ArrayList:
List<Playlist> playlists = new ArrayList<>();
playlists.add(new Playlist("Rock"));
// ...
Playlist p = playlists.get(index);

If you want to safely remove and get correct keys after, you must iterate the Map
int count = 0;
boolean found = false;
Iterator<Map.Entry<Integer,String>> iter = TestMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer,String> entry = iter.next();
if("Sample".equalsIgnoreCase(entry.getValue())){
iter.remove();
found = true;
}
if (found) {
// set the new key using count...
}
count ++;
}

first let me see if i understand your problem correctly or not . you like to reoder playlist after any delete operation. 1,2,3,4,5 . you delete 3 , then it should be 1,2,4,5 and not 1,2, ,4,5.
if above is true , best is use linkedhashmap collection. also case1 you can rewrite as
case 1: {
System.out.println("Lista playlist: ");
for (Playlist pll:Playlista.values()) {
System.out.println(i + ". " + pll.Nazwa());
}
break;
}

Related

How to exit all multiple nested methods at once

I've been following Tim Buchalka's course Java Programming Masterclass for Software Developers and I've been modifying his program from lesson 118.
I want to update my list at the runtime while using the list iterator (navigate method). The program runs fine, but if I update my list, Java throws an error: ConcurrentModificationException
I have come up with the following solution:
Whenever a user performs a modification of the list, other methods run, and update the list and pass it to the navigate() method. By doing this, my program enters multi-level nested methods, and the problem comes up when a user wants to exit from the program (case 0: in navigate() method). User has to press 0 as many times as many nested methods were ran.
My initial idea was to count how many times navigate() was nested, then using for loop return as many times as it was nested. But later I understood it does not make sense
What can I do to exit from the program by using case 0: just once?
package com.practice;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;
public class List extends Traveler {
private LinkedList<String> linkedList;
private String tripName;
public List(String travelerName, int travelerAge, String tripName) {//it has to have same amount of parameters or more with super constructor!
super(travelerName, travelerAge);
this.tripName = tripName;
this.linkedList = new LinkedList<>();
}
public List(){} //it has to have same amount of parameters or more with super constructor!
public LinkedList<String> getLinkedList() {
return linkedList;
}
public String getTripName() {
return tripName;
}
private void removeCity(LinkedList<String> cityList, String deletedCity) {
if(cityList.remove(deletedCity)) {
System.out.println(deletedCity + " has been removed");
} else System.out.println("Could not find the city you want to remove");
List.navigate(cityList);
}
//adds a new city and update the list without an error
private void noExceptionError(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator();
while((listIterator.hasNext())) {
int comparison = listIterator.next().compareTo(cityName);
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous();
break;
}
}
listIterator.add(cityName);
List.navigate(listOfCities);
}
private void loadToList(LinkedList<String> listOfCities) {
alphabeticallyAdd(listOfCities, "Poznan");
alphabeticallyAdd(listOfCities, "Gdansk");
alphabeticallyAdd(listOfCities, "Szczeczin");
alphabeticallyAdd(listOfCities, "Warszawa");
alphabeticallyAdd(listOfCities, "Lodz");
alphabeticallyAdd(listOfCities, "Wroclaw");
List.navigate(listOfCities);
}
private void alphabeticallyAdd(LinkedList<String> listOfCities, String cityName) {
ListIterator<String> listIterator = listOfCities.listIterator(); //just a setup; doesn't point to the 1st element
while((listIterator.hasNext())) {
//if value is greater, the word that is in the list is alphabetically bigger, thus, put it before the list element
//if equal, it is duplicate! return false
// else it is less, thus, we have to move further in the list
int comparison = listIterator.next().compareTo(cityName); //retrieves the 1st value and goes to the next
if(comparison == 0) {
System.out.println(cityName + " has been already added to the list");
return;
} else if(comparison > 0) {
listIterator.previous(); //because we've used .next() in the int comparison initialization
listIterator.add(cityName); //don't use linkedList.add because it doesn't know the int comparison, so cannot properly add!!!
return;
}
}
listIterator.add(cityName); //adding at the end of the list
}
public static void navigate(LinkedList<String> listOfCities) {
Scanner userChoice = new Scanner(System.in);
List travelListObject = new List();
ListIterator<String> listIterator = listOfCities.listIterator();
boolean goingForward = true;
while(true) {
Main.menu();
int choice = userChoice.nextInt();
userChoice.nextLine(); //takes care of enter key problem
switch(choice) {
case 0:
System.out.println("Goodbye");
//possible improvement
/* for(int i = 0; i <= List.amountNestedMethods; i++) {
return;
}*/
return;
case 1: //moving forward
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
}
if(listIterator.hasNext()) {
System.out.println(listIterator.next());
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
goingForward = true;
} else {
System.out.println("No more cities in the list");
goingForward = false;
}
break;
case 2: //moving back
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
Traveler.setNumberVisitedCities(Traveler.getNumberVisitedCities() + 1);
System.out.println(listIterator.previous());
} else {
System.out.println("You're at the beginning of the list");
goingForward = true;
}
break;
case 3:
Main.printCities(listOfCities);
break;
case 4:
break;
case 5:
System.out.println("Write new city");
String addedCity = userChoice.next();
travelListObject.noExceptionError(listOfCities, addedCity);
break;
case 6:
System.out.println("Write the city you want to delete");
String deletedCity = userChoice.next();
travelListObject.removeCity(listOfCities, deletedCity);
break;
case 7:
System.out.println("You have been in " + Traveler.getNumberVisitedCities() + " cities in total");
break;
case 9:
travelListObject.loadToList(listOfCities);
break;
default:
System.out.println("Something weird happened. Try to choose an option again");
}
}
}
}
If you want to exit the program you can simply call System.exit(n), where the n is an integer return code (the convention being that code 0 means normal execution and other values indicate some sort of error).

How can I stop a method updating an array outside of it

Hoping for some help - I've been asked to write a hotel room system using methods for uni. All has been going well until I try to order the array alphabetically.
I have managed to get it to order within the method but it updated the main array (hotel). I want it to keep it within the order method, if that makes sense?
I've included a cut down version below without all the functions.
Currently it will reorder the array hotel so if you view the rooms the array will print like 'e,e,e,etc, George, Peter, Robert' instead of keeping its original form 'e, Robert, Peter, e,e,etc, George'
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
String[] hotelRef = new String[12];
String[] hotel = new String[12];
initialise(hotel); //initialise
while (roomNum < 13) {
System.out.println("Please select from the menu:");
System.out.println("V : View rooms");
System.out.println("O : Order Guests alphabetically");
String selection = input.next();
switch (selection) {
//There are more switch cases on the original version
case "O":
order(hotel);
break;
default:
System.out.println("");
}
}
}
private static void order(String[] hotelRef) {
int j;
boolean flag = true; //will determine when the sort is finished
String temp;
String[] order = new String[12];
order = hotelRef;
while (flag) {
flag = false;
for (j = 0; j < order.length - 1; j++) {
if (order[j].compareToIgnoreCase(order[j + 1]) > 0) {
//ascending sort
temp = order[j];
order[j] = order[j + 1]; // swapping
order[j + 1] = temp;
flag = true;
}
}
}
for (int y = 0; y < order.length; y++) {
if (!order[y].equals("e")) {
System.out.println("Room " + y + " is occupied by " + order[y]);
}
}
System.out.println("Ordering completed");
}
You should clone the hotelRef instead of assigning the reference like this order = hotelRef;
You could do the following while creating the order array :
String[] order = new String[hotelRef.length]; // to make sure that order has the right size.
and instead of order = hotelRef;
for (int i=0;i<order.length;i++)
order[i]=hotelRef[i]; // thereby cloning
or use System.arraycopy() or any other method to accomplish cloning the array.
You can make copy of hotel array in your order method:
String[] hotelCopy = new String[hotelRef.length];
System.arraycopy(hotelRef, 0, hotelCopy, 0, hotelRef.length);
And then just use hotelCopy inside your order method.
The problem lies with the following line
order = hotelRef;
Change it to
order = hotelRef.clone();
Though you are creating a new object, you have assigned the reference to outer object only. So whatever changes you make in the inner object it will be reflected to the outer object.

Finding duplicates in an array of objects

The purpose of this project is to make a pokedex that adds and holds all the pokemon passed in by user input. When the user inputs a pokemon that is already stored in the pokedex the word "duplicate" is supposed to be printed to the console. The word duplicate is printed even though there are no actual duplicates within the object array. Here is my output from the console :
Welcome to your new PokeDex!
How many Pokemon are in your region?: 3
Your new Pokedex can hold 3 Pokemon. Let's start using it!
List Pokemon
Add Pokemon
Check a Pokemon's Stats
Sort Pokemon
Exit
What would you like to do? 2
Please enter the Pokemon's Species: red
Duplicate
Now here is all the code used that could possibly be making this error
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your new PokeDex!");
System.out.print("How many Pokemon are in your region?: ");
int size = input.nextInt();
Pokedex pokedex = new Pokedex(size);
System.out.println("\nYour new Pokedex can hold " + size + " Pokemon. Let's start using it!");
int choice = 0;
boolean done = false;
while (!done) {
System.out.println("\n1. List Pokemon\n2. Add Pokemon\n3. Check a Pokemon's Stats" + "\n4. Sort Pokemon\n5. Exit");
System.out.print("\nWhat would you like to do? ");
choice = input.nextInt();
switch (choice) {
case 1:
String[] pokemonList = pokedex.listPokemon();
if (pokemonList == null)
System.out.println("Empty");
else
for (int i = 0; i < pokemonList.length; i++) {
System.out.println((i + 1) + ". " + pokemonList[i]);
}
break;
case 2:
System.out.print("\nPlease enter the Pokemon's Species: ");
String species = input.next();
pokedex.addPokemon(species);
break;
}
}
}
}
In the following class I have the actual method that adds the pokemon and the constructor for Pokedex
public class Pokedex {
Pokemon[] pokedex;
String pokeArray[];
public Pokedex(int size) {
pokedex = new Pokemon[size];
pokeArray = new String[size];
}
public boolean addPokemon(String species) {
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++) {
if (pokedex[i] == null) {
pokedex[i] = stuff;
}
else if (i < pokedex.length && pokedex[i] != null) {
System.out.println("Max");
}
if (pokedex[i].getSpecies().equalsIgnoreCase(species)) {
System.out.print("Duplicate");
break;
}
}
return false;
}
}
Sorry for the mass amounts of code I just need help tracing where this unexpected result is coming from.
The reason it's doing that is because of this bit of code here:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if (pokedex[i] == null)
pokedex[i] = stuff;
else if (i < pokedex.length && pokedex[i] !=null)
System.out.println("Max");
if(pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.print("Duplicate");
break;
}
}
return false;
}
The problem is just a little bit of syntax missing. In your for loop, you check to see if
A) there are any empty spots in the array
B) if every element in the array up to the user inputted size is full
and C) if any element in the array matches the one we're trying to add.
The problem you're encountering is because your C is an if instead of an else if. Because A sees the index is null, it assigns the new Pokemon to the Pokedex. Then because C is an if instead of an else if, it runs after you assign the new Pokemon and sees the Pokemon we just added and says it's a duplicate. Changing it to an else if would fix this.
Also, since there was no break; in A, it would assign every element of the array to the first one entered, causing any further additions to call Max. I edited the code and this is what I had that worked for me:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if(pokedex[i] !=null && pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.println("Duplicate");
break;
}
else if (pokedex[i] == null)
{
pokedex[i] = stuff;
break;
}
else if(i + 1 == pokedex.length)
{
System.out.println("Max");
break;
}
}
return false;
}
Also, out of curiosity, why is the addPokemon() function a boolean? You return a value (albeit arbitrarily) and then never do anything with that value. You could just make it a void, have it return nothing, and it would work just as fine.

A* algorithm taking too long to solve

I have to use an algorithm to find a path for a school project. I have a sequence of 12 goals on the map, which must be reached before the end of the path. The map is a 70x70 array. What I already did:
I find all the goals and add in a list
The goals are marked by numbers 10 to 21, and i put on a list 0 to 12. (21 IS THE last goal)
private casa[] acharCasas(){
casa[] casas = new casa[12];
for (int linha = 0; linha < jogo.getMapa().length; linha++) {
for (int coluna = 0; coluna < jogo.getMapa()[0].length; coluna++) {
if(jogo.getMapa()[linha][coluna] >= 10 && jogo.getMapa()[linha][coluna] <= 21){
casas[jogo.getMapa()[linha][coluna]-10] = new casa (linha,coluna);
}
}
}
return casas;
}
I make heuristics total cost + distance from other houses unvisited
casas_visitadas are the number of visited goals, and posL = row, posC = Col. What I wanted to do is calculate the distance from where you are to the next uncompleted objective, + distance from this objective to the next objective... to the final goal.
public double distanciaDasOutrasCasas(){
double somaTotal = 0;
int posL = linha,posC = coluna;
for (int i = casas_visitadas; i < 12; i++) {
somaTotal += Math.sqrt(
Math.pow( (double) (casas[i].linha - posL),2) +
Math.pow( (double) (casas[i].coluna - posC),2)
);
posL = casas[i].linha;
posC = casas[i].coluna;
}
return somaTotal;
}
I check all possible movements
And I add them to the ArrayList. Here are the constructors:
public ArrayList<Direcao> movimentosPossiveis(){
ArrayList<Direcao> movimentos = new ArrayList<>();
if (linha > 0) movimentos.add(Direcao.CIMA); // if isnt the first row add UP
if (coluna > 0) movimentos.add(Direcao.ESQUERDA);//if inst the first col add LEFT
if (linha < jogo.getMapa().length) movimentos.add(Direcao.BAIXO); // last row add down
if (coluna < jogo.getMapa()[linha].length) movimentos.add(Direcao.DIREITA); // add right
return movimentos;
}
public ArrayList<cell> permutaCelula(){
ArrayList<Direcao> movimentos = movimentosPossiveis();
ArrayList<cell> novasCelulas = new ArrayList<>();
for (Iterator<Direcao> iterator = movimentos.iterator(); iterator.hasNext();) {
Direcao D = iterator.next();
switch (D){
case CIMA:
novasCelulas.add(
new cell(this /*father*/, Direcao.CIMA /*direction from father */, custo_total /*total cost*/, linha-1/*row-1*/, coluna/*col*/, casas_visitadas/*goals visiteds*/)
);
break;
case BAIXO:
novasCelulas.add(
new cell(this, Direcao.CIMA, custo_total, linha+1, coluna, casas_visitadas)
);
break;
case ESQUERDA:
novasCelulas.add(
new cell(this, Direcao.CIMA, custo_total, linha, coluna-1, casas_visitadas)
);
break;
case DIREITA:
novasCelulas.add(
new cell(this, Direcao.CIMA, custo_total, linha, coluna+1, casas_visitadas)
);
break;
}
}
return novasCelulas;
}
public double convertePesoDoChao(){
System.out.println(" L " + this.linha + " Coluna "+ coluna);
int chao = jogo.getMapa()[this.linha][this.coluna];
switch (chao) {
case 0:
return 200; //rock field, slowest field
case 1:
return 1;
case 2:
return 3.5;
case 3:
return 5;
case 22:
if(quantidadeDeCavaleirosVivos() != 0) return Double.MAX_VALUE; // cant go to master without find all goals
finalizado = true; // found
caminhoFinal = converteCelulaParaMovimentos(); // converts cells movements
return 0;
default:
casas_visitadas++;
return 0;
}
}
public cell(cell pai, Direcao oPaiMexeuPraQualDirecao, double custo_total, int linha, int coluna, int casas_visitadas) {
this.pai = pai; // father
this.oPaiMexeuPraQualDirecao = oPaiMexeuPraQualDirecao; // direction from father
this.linha = linha; //row
this.coluna = coluna; // col
this.casas_visitadas = casas_visitadas; //goals visited
this.custo_total = custo_total + convertePesoDoChao(); // fathers total cost + field cost
}
public cell(int linha, int coluna) { //starter cell
this.linha = linha;
this.coluna = coluna;
this.custo_total = 0;
this.pai = null;
}
The heuristic
my heuristic is total cost + distancefromgoals
public double heuristica(){
return custo_total *10 + distanciaDasOutrasCasas();
}
Primary loop
if(!finalizado){
this.jogo = jogo;
colunaInicial = jogo.getColuna();
linhaInicial = jogo.getLinha();
casas = acharCasas();
ArrayList<cell> franja = new ArrayList<>();
franja.add(new cell(linhaInicial,colunaInicial));
while(!finalizado){
Collections.sort(franja);
franja.addAll(franja.get(0).permutaCelula());
franja.remove(0);
}
}
The problem
It's taking too long, over three hours total, to find the way... any tips? I checked on the Netbeans profiler, and the problem is sorting the array.
My full code is here
obs: on full code, a game call the action move, and on the first call I need to find the best way, and save it, later I just pop the stack of movements
obs2: sorry my bad english, i used google translator on some parts

File Writing Issues w/ ArrayList

EDIT: Program now writes the first existing score only, and as follows:
File size(in lines)-
0- Writes as normal.
1- Prompts for initials, output shows user score was added to myscores, but the first score is the one added to the file.
2+- Similar to second, no prompt for initials, first score is written twice to file.
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.text.*;
/* Notes:
* High Scores Class:
* Used to read/write high scores text file
* */
/*
* To do:
* Fix reading/writing file
* Fix sort as needed
* FILTER OUT WHITESPACE WHEN READING
*/
public class HighScores
{
//user will input their 3 initials, must be 3
public ArrayList<String> filearr;//hold file contents
public BufferedReader hsds;//read initials in
public ArrayList<Score> myscores;//hold all existing scores
public ArrayList<String> vals;//hold filearr contents to be split and parsed
public HighScores() //constructor
{
myscores = new ArrayList<Score>();
vals = new ArrayList<String>();
hsds = new BufferedReader(new InputStreamReader(System.in));//for user input
filearr = new ArrayList<String>();//holds values to be written to file
System.out.println("File created.");
}
public void populate(Score uscore)
//argument is score generated by user
//this is called after game finishes
//handles score(write or no?
{
Integer thescore = uscore.myscore;
switch (filearr.size())
{
case 2://doesnt prompt for initials, writes first score twice each on a new line
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
String strpos = "" + ((vals.get(0)).charAt(3));//remember strings are arrays!
for (int i = 0; i < vals.size(); i++)
{
Score temp = new Score();
String tempstr = vals.get(i);
temp.initials = (tempstr.split(strpos)[0]);
temp.myscore = Integer.parseInt((tempstr.split(strpos)[2]));
myscores.add(temp);
}
int ssize = myscores.size();
BubbleSort bsort = new BubbleSort();
bsort.bubbleSort(myscores, ssize);//ssize is current size of scores
System.out.println("Unsorted scores");
for(int i = 0; i < myscores.size(); i++)
{
System.out.println("Score " + i + " : ");
System.out.println("inits: " + (myscores.get(i).initials));
System.out.println("myscore: " + ("" +(myscores.get(i).myscore)));
}
int max = myscores.size();
int y = 0;
Score sscore = new Score();
sscore.myscore = thescore;
if(sscore.myscore > (myscores.get(y)).myscore)//sorting algorithm
{
try
{
System.out.println("Please enter 3 initials to identify your high score.");
String tinitials = "" + ((hsds.readLine()).toUpperCase());
//initials are always formatted as upper case
if (tinitials.length() > 3)
{
String temp = tinitials.split(strpos)[0];
sscore.initials = temp;
}
else
{
sscore.initials = tinitials;
}
hsds.close();
}
catch (Exception e)
{
e.printStackTrace();
}
if(sscore.myscore < (myscores.get(max - 1)).myscore)//smaller than largest
{
System.out.println("bigger, sm max");
myscores.set(y, sscore);//in at 0
y++;//now 1
while ((myscores.get(y)).myscore < sscore.myscore)
{
myscores.set(y-1, myscores.get(y));//shift this one down
myscores.set(y, sscore);//fill the hole
y++;//ends up at 5
}
}
else if(sscore.myscore > (myscores.get(max-1)).myscore)//bigger than largest
{
System.out.println("bigger, gr max");
Score temp = (myscores.get(max-1));
myscores.set(max-1, sscore);//in at end
y++;
while(y < (max-1))
{
myscores.set(y-1, myscores.get(y));//shift this one down
myscores.set(y, myscores.get(y+1));//fill the hole
y++;//ends up at 5
}
myscores.set(max-2, temp);
}
else if((sscore.myscore).equals((myscores.get(max-1)).myscore))//equal to largest
{
System.out.println("bigger, eq max");
y++;//now 1
while ((myscores.get(y)).myscore < sscore.myscore)
{
myscores.set(y-1, myscores.get(y));
myscores.set(y, sscore);
y++;
}
myscores.set(y-1, sscore);
}
else
{
System.out.println("Oops.");
}
}
else//smaller than first element
{
System.out.println("too small");
}//end sort
System.out.println("Sorted scores");
for(int i = 0; i < myscores.size(); i++)
{
System.out.println("Score " + i + " : ");
System.out.println("inits: " + (myscores.get(i).initials));
System.out.println("myscore: " + ("" +(myscores.get(i).myscore)));
}
break;
case 0://writes first score once
Score newscore = new Score();
newscore.myscore = thescore;
try
{
System.out.println("Please enter 3 initials to identify your high score.");
String tinitials = "" + ((hsds.readLine()).toUpperCase());
//initials are always formatted as upper case
if (tinitials.length() > 3)
{
strpos = "" + (tinitials.charAt(3));
String temp = tinitials.split(strpos)[0];
newscore.initials = temp;
}
else
{
newscore.initials = tinitials;
}
}
catch (Exception e)
{
e.printStackTrace();
}
myscores.add(newscore);
break;
case 1://writes first score again on separate line
newscore = new Score();
newscore.myscore = thescore;
strpos = "" + ((vals.get(0)).charAt(3));//remember strings are arrays!
try
{
System.out.println("Please enter 3 initials to identify your high score.");
String tinitials = "" + ((hsds.readLine()).toUpperCase());
//initials are always formatted as upper case
if (tinitials.length() > 3)
{
strpos = "" + (tinitials.charAt(3));
String temp = tinitials.split(strpos)[0];
newscore.initials = temp;
}
else
{
newscore.initials = tinitials;
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (int i = 0; i < vals.size(); i++)
{
Score temp = new Score();
String tempstr = vals.get(i);
temp.initials = (tempstr.split(strpos)[0]);
temp.myscore = Integer.parseInt((tempstr.split(strpos)[2]));//works, idk why
myscores.add(temp);
}
bsort = new BubbleSort();
if (newscore.myscore > (myscores.get(0)).myscore)
{
myscores.add(newscore);
}
else
{
bsort.bubbleSort(myscores, myscores.size());
}
break;
default:
System.out.println("Invalid file supplied.");
break;
}
}
public void Save(PrintWriter writeme)//write everything to a file, filearr should be
//the same size as it was upon object construction
{
for (int i = 0; i < myscores.size(); i++)
{
filearr.add(myscores.get(i).initials + " " + ("" + (myscores.get(i).myscore))); //copy the finished list over
writeme.println(filearr.get(i)); //write the list to the high scores file
//writeme is myout in dsapp.java
}
}
}
The classes not shown are Score(score object template), Encrypter(array generation and difficulty selection), BubbleSort(bubble sort algorithm), and DSApp(application file, draws GUI and performs file operations). Comments should explain everything; I can supply more code as needed. Any and all help would be greatly appreciated.
IndexOutOfBoundsExceptions on:
temp.myscore = Integer.parseInt((tempstr.split(strpos)[1]));
means that the array returned by tempstr.split(strpos) has less than 2 items (0 or 1). It should be fairly easy to add a print statement there or debug the program step by step to figure out why.
inability to write properly to a file
that's a bit vague (do you get an exception? the file is created but invalid? etc.)

Categories

Resources