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.)
Related
I was not able to shrink the specific element in an array. It copy the last element of the array and it will stay the same size.
Output:
1. Ramburat - 100 - PASSED
2. Ramburat - 100 - PASSED
Possible Output
1. Ramburat - 100 - PASSED
Source code for Deletion of an Element
public static void deleteStudent(String full_name)
{
int found = 1;
int delindex = -1;
for (int i= 0; i<count; i++)
{
if(name[i].equalsIgnoreCase(full_name))
{
// If matched then change the value of found to 1
found = 1;
// Store index of student to be deleted
delindex = i;
break;
}
}
// If student name is not found then value of flag remains unchanged
// Display the error that student not found
if(found == -1)
System.out.println("Error : No such student found!!!");
else
{
// Push all elements from index i+1 to last, 1 step back
for(int i=delindex; i<count-1; i++)
{
name[i] = name[i+1];
grade[i] = grade[i+1];
result[i] = result[i+1];
}
System.out.println("Student Details deleted Successfully.");
}
}
Here in this source code, the last part of my code I used to push back the data in order for the chosen name should be removed. but it still in the same size and it prints double.
Source code for ShowAllStudent
public static void showAllStudents()
{
// if count is 0 then no students in the list
if(count == 0)
{
System.out.println("There are no registered student in ISCP");
}
else
{
// Loop from index 0 to count of arrays
for(int i=0; i<count; i++)
{
System.out.println(i+1+". " + name[i] + " - " + grade[i] + " - " + result[i]);
}
}
}
Source code for Public static void main
public static void main (String [] args)
{
enlistStudent("Doyoung", 50);
enlistStudent("Ramburat", 100);
deleteStudent("Doyoung");
showAllStudents();
}
I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}
I've been trying to switch an older assignment over from an array to an arraylist, but for whatever reason my find method is not working when I modify it to use arrayList.. Seems to always be returning -1.
This is part of a large class so I don't want to include everything unless completely necessary, but I did include the declarations in case they are important:
public class Switch {
private SwitchEntry[] camTable;
private int numEntries;
private int maxEntries;
public Switch() {
camTable = new SwitchEntry[100]; // default value
numEntries = 0;
maxEntries = 100;
}
public Switch(int maxEntries) {
camTable = new SwitchEntry[maxEntries];
numEntries = 0;
this.maxEntries = maxEntries;
}
Original:
public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable[i].getAddress())){
found = i;
break;
}
return found;
}
Modified:
public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable.get(i).getAddress())){
found = i;
break;
}
return found;
}
Where numEntries is modified & where the new entries are added into the arrayList:
public void processFrame(Frame inFrame) {
// first, add source MAC to camTable if not already there
if (find(inFrame.getSource()) == -1) {
if (numEntries >= maxEntries) {
System.out.println ("Error...camTable is full - cannot add " + inFrame.getSource());
} else {
camTable.add(new SwitchEntry(inFrame.getSource(), inFrame.getPort())); //PROBLEM LINE
System.out.println ("Adding " + inFrame.getSource() + " to camTable");
}
}
//process frame
int index = find(inFrame.getDestination());
if (index != -1){
System.out.print ("Sending frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out port " + camTable.get(index).getPort() );
} else {
System.out.print ("Flooding frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out all ports" );
}
}
Solution:
camTable.add(numEntries++, new SwitchEntry(inFrame.getSource(),inFrame.getPort()));
Try This
public int find (MACAddress source) {
int found = -1;
ArrayList<MACAddress> camTable = new ArrayList<MACAddress>();
ListIterator<MACAddress> itr = camTable.listIterator();
while(itr.hasNext()){
MACAddress tempAdd = itr.next();
if(source.getAddress().equals(tempAdd.getAddress())){
found = itr.nextIndex();
return found;
}
return found;
}
I assume in ArrayList you store the objects of MACAddress. in if condition i check the source.getAddress to tempAdd.getAddress() is same then it will retun index of ArrayList. here ArrayList is local variable but you can create as a class variable
Use Contain method of collection.(ArrayList)
http://www.tutorialspoint.com/java/util/arraylist_contains.htm
Solution was straight-forward and just an oversight by me. All I had to do was add numEntries back into my add statement, which I neglected to fix after changing from an array to arrayList
Solution is posted in the original question now:
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;
}
I've got some problems with the topological sorting. It can find lops, but it counts some of the tasks (or "nodes" if you want to call it) several times. I think the problem is something with how I read or the Edge class, but I just can't see where it goes wrong. Any help would be really appreciated :)
enter code here
import java.util.*;
import java.io.*;
import java.lang.*;
class Task {
int id, time, staff;
int depA, depB;
String name;
int eStart, lStart;
Edge outEdge;
int cntPredecessors;
boolean visited;
Task(int id, String name, int time, int staff) {
this.id = id;
this.name = name;
this.time = time;
this.staff = staff;
visited = false;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
class Edge {
Task id, name, time, staff;
Edge neste;
Task fra, til;
Edge(Task id) {
this.id = id;
}
}
class Input {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("enter a filename!");
System.exit(1);
} else if (args.length == 1) {
String fil = args[0]+".txt";
LesFraFil(fil);
// skrivUt();
topSort();
} else {
System.out.println("too many parameters, try again...");
}
}
static int antTask;
static Task[] ids;
static int tTid;
static void LesFraFil(String fil) {
int i = 0;
int j;
try {
String lest;
Scanner in = new Scanner(new FileReader(fil));
Edge til;
int counter = 0;
antTask = in.nextInt();
ids = new Task[antTask];
System.out.println(antTask);
while (in.hasNextLine()) {
lest = in.nextLine();
// hvis tom linje, så hopper den over
if(lest.trim().length() == 0) continue;
String split[] = lest.split("\\s+");
int id = Integer.parseInt(split[0]);
String act = split[1];
int tid = Integer.parseInt(split[2]);
int staff = Integer.parseInt(split[3]);
int depA = Integer.parseInt(split[4]);
tTid += tid;
ids[i] = new Task(id, act, tid, staff);
j = 4;
/*
* Lesingen av inputen skal avbrytes når den leser 0.
* j er den som holder på hvor langt vi er i split arrayet
* når den møter på 0
*/
while(split[j].compareTo("0") != 0) {
int tmp = Integer.parseInt(split[j])-1;
// System.out.println(tmp+1 + " Aktivitetens navn : " + act); //+ " tiden aktiviteten tar tid: " + tid + " avhengihet: " + split[j]);
j++;
if (ids[tmp] == null) {
ids[tmp] = new Task(id, act, tid, staff);
ids[tmp].visited = true;
}
ids[i].cntPredecessors++;
if(ids[tmp].outEdge == null) {
ids[tmp].outEdge = new Edge(ids[i]);
} else {
til = ids[tmp].outEdge;
while(til.neste != null) {
til = til.neste;
}
til.neste = new Edge(ids[i]);
}
}
counter++;
i++;
}
if (antTask == counter) {
System.out.println("Lesinga gikk som planlagt av fil: " + fil);
System.out.println("Total arbeidstid: " + tTid);// + antTask + " == " + counter );
} else {
System.out.println("Noe gikk galt avslutter!");
System.out.println(antTask + " || " + counter);
System.exit(2);
}
in.close();
} catch (Exception e) {
System.err.println("ERROR!" + e.getMessage());
}
}
static void skrivUt() {
for (Task sort : ids) {
System.out.print(sort.id + " " + sort.name);
Edge til = sort.outEdge;
while (til != null) {
System.out.print(" " + til.id.id);
til = til.neste;
}
System.out.println();
}
}
static void topSort() {
LinkedList<Task> list = new LinkedList<Task>();
ArrayList<Task> array = new ArrayList<Task>();
Task temp;
int count = 0;
int totalTime = 0;
// Legger taskene i lista
for (Task t : ids) {
if(t.cntPredecessors == 0) {
list.add(t);
totalTime += t.time;
// System.out.println(t);
t.visited = true;
}
}
for (Task t : ids) {
if(t.cntPredecessors == 1) {
list.add(t);
totalTime += t.time;
// System.out.println(t);
t.visited = true;
}
}
// går i evig løkke til lista er tom.
while (!list.isEmpty()) {
temp = list.pop(); // fjerner elementet fra lista
array.add(temp); // legger inn i arraylisten
count++;
// System.out.println(temp);
for(Edge til = temp.outEdge; til!=null;til=til.neste) {
til.id.cntPredecessors--;
if(til.id.cntPredecessors==0) {
list.add(til.id);
}
}
}
if(count < antTask) {
System.out.println("A loop has been found. Terminating...");
System.exit(0);
}
System.out.println("Topological sort: " + Arrays.toString(array.toArray()));// den sorterte "arraylisten"
System.out.println("Total time spend: " + totalTime);
}
} // End class Input
Here is an example of an input file
8
1 Build-walls 4 2 5 0
2 Build-roofs 6 4 1 0
3 Put-on-wallpapers 1 2 1 2 0
4 Put-on-tiles 1 3 2 0
5 Build-foundation 4 2 0
6 Make-floor 2 2 5 0
7 Put-carpet-floor 4 2 6 2 0
8 Move-in 4 4 3 7 0
The problem is with this loop (inside topSort()):
for (Task t : ids) {
if(t.cntPredecessors == 1) {
list.add(t);
totalTime += t.time;
// System.out.println(t);
t.visited = true;
}
}
You just need to remove it.
Reason: this loop adds to list nodes that have 1 incoming edge. Later (in the while loop), it is possible that for these nodes the cntPredecessors field will be decreased to 0 which will make them being pushed back onto list, thus counted twice.
In the future, please try to narrow down your code to something that contains less "noise", that is: the smallset (or nearly smallest) code that illustrates the problem. This will ease the understanding on potential answerers (not to mention that it may help you see the problem yourself).