Delete Method without Array List - java

I need to implement a delete method WITHOUT USING AN ARRAY LIST. I need to use a set of loops to do it. Here is my delete method and add method as well as any other important variables used. Any advice on what is wrong with my code would be great.
EDITED: Changed the comparing of references to values. Seems to work repeatedly.
final int MAX_DEVICES = 5;
// Array of devices
private Device list[] = new Device[MAX_DEVICES];
// Number of Devices currently in the list
// "Valid" Devices are stored in cells 0 - (numDevices - 1)
private int numDevices = 0;
Scanner stdin; // read from stdin
private void Add()
{
String thisName;
int numThisRead;
float thisInitVal;
thisName = stdin.next();
numThisRead = stdin.nextInt();
thisInitVal = stdin.nextFloat();
if(numDevices > MAX_DEVICES)
System.out.println("The List was full. " + thisName +
" was not added to the list.");
else
{
Device myDevice = new Device(thisName, numThisRead, thisInitVal);
list[numDevices] = myDevice;
numDevices ++;
System.out.println(thisName + " device has been added to the list.");
}
}
private void Delete() //ASK QUESTION
{
String thisDelete;
thisDelete = stdin.next();
for(int i = 0; i < MAX_DEVICES; ++i)
{
if(list[i].getName().equals(thisDelete)) //if you find the name
{
System.out.println(list[i].getName() + " was deleted from the "
+ "list.");
for(int j = i; j < numDevices - 1; j++)
list[j] = list[j + 1];
numDevices--;
return;
}
}
System.out.println(thisDelete + " not deleted. It is not in the list.");
}

If you need to avoid using data type List, you can place the objects in the array. Then you can declare an array one element smaller than the current array and copy all the elements, except for the one you want deleted, over into the new array. Then return the new array.

Related

The content of an array is suspiciously doubled

I have been building an app that simulates the way a printer works. While designing the app, I have created the method below that splits a String content depending on the number of pages required. All the function seems to process the data correctly but I don't know why the method keeps doubling the content of an array it's supposed to return. Here's the method.
public ArrayList<String> splitContentIntoPages(){
int startPosition = 0;
int endIndexCalc = 0;
for(int i=0; i<getPages(); i++){
if((getContent().length() - endIndexCalc) >= getSize().getCapacity()){
System.out.println("Start " + startPosition);
endIndexCalc = startPosition + (getSize().getCapacity());
this.pagesContent.add(getContent().substring(startPosition, endIndexCalc));
startPosition += getSize().getCapacity();
System.out.println("End " + endIndexCalc);
}else{
this.pagesContent.add(getContent().substring(startPosition));
}
}
System.out.println("Size of the array " + this.pagesContent.size() + " getPages() " + getPages() + "");
for(int i=0; i<this.pagesContent.size(); i++){
System.out.println("The content :" + this.pagesContent.get(i));
}
return this.pagesContent;
}
I need some fresher eye on the issue. I have spent too much time on that trying to understand what's wrong. Thanks a lot guys!
Here's the version without debugs
public ArrayList<String> splitContentIntoPages(){
int startPosition = 0;
int endIndexCalc = 0;
for(int i=0; i<getPages(); i++){
if((getContent().length() - endIndexCalc) >= getSize().getCapacity()){
endIndexCalc = startPosition + (getSize().getCapacity());
this.pagesContent.add(getContent().substring(startPosition, endIndexCalc));
startPosition += getSize().getCapacity();
}else{
this.pagesContent.add(getContent().substring(startPosition));
}
}
return this.pagesContent;
}
this is the test entry extraxt. Basically the method aboe is processing the string of chars
that's the outcome. Basically, the string is supposed to be split into the number of pages - in this case 2. However, the array that is holding the split element of the strings holds 4 pieces of strings instead of two. It's all doubled. And I have no idea why
Either clear this.pagesContent at the beginning of splitContentIntoPages() or create new ArrayList<String> newA = new ArrayList<String>() at the beginning, add everythig to this new arrayList and at the end of splitContentIntoPages() do this.pagesContent = newA

Search and remove item from array

Does anyone why when the search value matches a value stored in array it doesn't remove that item?
String titles = "";
String lengths = "";
for (int i = 0; i < numOfSongs; i++) {
titles += songTitles[i] + " ";
lengths += songLengths[i] + " ";
}
String search = JOptionPane.showInputDialog("Enter a song title to remove it or -1 to end:");
while (!search.equals("-1")) {
for (int i = 0; i < numOfSongs; i++) {
if (search.equalsIgnoreCase(songTitles[i])) {
songTitles[i] = songTitles[i + 1];
}
}
numOfSongs--;
JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);
search = JOptionPane.showInputDialog("Enter a song title to remove it or -1 to end:");
}
Many things are wrong with this code:
You never update titles and lengths inside your while loop, so whatever happens inside has no effect on what's printed in the dialog
When you find song title to remove, you copy the next song title to the current one, but don't copy anything else, so [a, b, c, d] will after removing b change to [a, c, c, d] - you need to shift everything behind the deleted element left by one position
When you find song title to remove, you assume the i+1th position is valid - this isn't true if you remove the last song on the list, that would either fail with ArrayIndexOutOfBounds exception or copy some garbage from behind the currently valid playlist
You're never updating songLengths array
Concatenating strings in a loop using += is very ineffective - use StringBuilder instead
Sorry this took a while, but hopefully it's pretty comprehensive.
I am assuming that song title and song length are supposed to correspond with one another, so that if you remove the title you also remove the length? It may be good to create a class, e.g. Song, which has a field for both title and length. There are more methods you can add, e.g. setters, default constructor, etc. You can also include more fields like Song Artist, year, etc. I'm just including those required for your program to run.
I'll use red's suggestion of an ArrayList, so you can see what they meant (in case you haven't learned what that is)
public class Song {
String title; //these are known as fields, or instance variables
String length;
public Song(String title, String length) {
this.title = title;
this.length = length;
}
public String getTitle() {
return title;
}
public String getLength() {
return length;
}
//you can format this differently. Just keeping it simple though. If you don't include toString() method in this class, you will run into some problems if you try to print the object itself.
public String toString() {
return "title = " + title + " length = " + length + "\n";
}
From here, in your main method you can do...
ArrayList<Song> playlist = new ArrayList<>();
//here, inside a do-while loop, get input for each song, then store into strings, let's call them songTitle and songLength. I'm not showing this step since I don't know where you want the input to come from, but I'm sure you can figure this bit out. ;)
Then we create objects and add them to your list like so:
Song song = new Song(songTitle, songLength); //creates a new object with arguments songTitle and songLength
playlist.add(song); //adds object to array list.
Once you have your playlist set up, we return to your question regarding song removal, and here is where Lists(there are different ones you can use)/Objects really make things far simpler.
Iterator<Song> songIt = playlist.iterator();
while (!search.equals("-1") && songIt.hasNext()) {
if (search.equalsIgnoreCase(songIt.next().getTitle())) {
songIt.remove();
}
}
And printing is simple too.
for (int i = 0; i < playlist.size(); i++) {
System.out.println(playlist.get(i);
}
-EDIT-
To put into perspective, here is what you would have to do for removal in your program using array and without objects.
int removeCount = 0;
while (!search.equals("-1")) {
for (int i = 0; i < songTitles.length; i++) {
if (search.equalsIgnoreCase(songTitles[i])) {
for (int j = i; j < songTitles.length - 1; j++) {
songTitles[j] = songTitles[j + 1];
songLengths[j] = songLengths[j + 1];
removeCount ++;
}
}
}
}
String remainingTitles[] = new String[songTitles.length - removeCount];
String remainingLengths[] = new String[songTitles.length - removeCount];
for (int i = 0; i < temp.length; i++) {
remainingTitles[i] = songTitles[i];
remainingLengths[i] = songLengths[i];
}
Suffice it to say, this is much more ugly, and there's many more places where you can make a stupid mistake that may or may not throw an exception.

Java - Passing arguments to constructor to put into an array

So basically I'm passing 3 strings to my constructor which will then place them in already made arrays within my object/class, i'm having a bit of trouble trying to figure this out.
This is my object class
public class results {
String[] matchnumber = new String[9];
String[] score1 = new String[9];
String[] score2 = new String[9];
int i = 0;
public results() {
}
public void addResults(String token, String token2, String token3) {
matchnumber[i] = token;
score1[i] = token2;
score2[i] = token3;
i++;
}
This is my main class
> do {
> System.out.println("Enter the current Round number between 1-26");
> roundnumber = kb.nextInt();
> } while (roundnumber <= 0 || roundnumber >= 27);
> results[] resultsarray = new results[(roundnumber)];
>
> for (int i = 0; i < resultsarray.length; i++) {
> File myFiles2 = new File("Round" + (i+1) +".txt");
> Scanner inputFiles2 = new Scanner(myFiles2);
>
> while (inputFiles2.hasNext()) {
> String str2 = inputFiles2.nextLine();
> String[] token = str2.split(",");
> System.out.println(token[0] + " " + token[1]+ " " + token[2]);
> resultsarray[i].addResults(token[0], token[1], token[2]); (NULL EXCEPTION ON THIS LINE)
> }
> }
As you can see Im scanning a text file to obtain 3 strings (text file contains lines of data). What i need help with is passing the 3 string tokens in my object and then saving it as an array and then processing the next batch of 3 strings into the next array index until i run out of strings in the current text file, whereby the next text file is opened and new instance of the results object is created and rinse and repeat. So yeah am i even close or completely off track lol.
You shouldn't assign values to the arrays in the results constructor, since the constructor only accepts the values for a single index of the array, and your current code will only use the first (0) index of each array.
You should use a constructor that takes no arguments, and use a different method to add the data to the arrays.
Your inner loop will then look like this :
resultsarray[i] = new results();
while (inputFiles2.hasNext()) {
String str2 = inputFiles2.nextLine();
String[] token = str2.split(",");
System.out.println(token[0] + " " + token[1]+ " " + token[2]);
resultsarray[i].addResults(token[0], token[1], token[2]);
}
Where addResults is a new method that contains the logic of your old constructor.

How to make a String from two set of list with alternate values

I have two lists which contains some values,I have to make String from them so that i will take the 1st value of first list and 1 st value of 2 nd list and also 2nd value of first list and 2 nd value of 2nd list and so on..Lets says those two lists contains the interview timings.So i am giving my code here
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
for(String a :interviewTimingToFrom1){
System.out.println("Timing 1:"+a);
}
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
for(String a :interviewTimingToFrom2){
}
The values contain in the 1 st and 2nd list are
Timing 1:12:00am
Timing 1:2:00am
Timing 2:1:00am
Timing 2:3:00am
So now i need to make a string like from 12.00am to 1.00 am ,from 2.00 am to 3.00am how i can do that .Please help
int maxSize = Math.max(interviewTimingToFrom1.size(),interviewTimingToFrom2.size());
StringBuilder result = new StringBuilder();
for (int i=0; i<maxSize; i++)
{
if (i < interviewTimingToFrom1.size())
result.append(interviewTimingToFrom1.get(i));
if (i < interviewTimingToFrom2.size())
result.append(interviewTimingToFrom2.get(i));
}
System.out.println(result.toString());
Try this;
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
if (interviewTimingToFrom1.size() == interviewTimingToFrom2.size()) {
int noOfSlots = interviewTimingToFrom1.size();
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom1.get(i));
}
} else {
System.out.println("No match");
int noOfSlots = (interviewTimingToFrom1.size() > interviewTimingToFrom2
.size() ? interviewTimingToFrom2.size()
: interviewTimingToFrom1.size());
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom2.get(i));
}
}

Adding to an ArrayList using input from GUI

I first created an arraylist in another part of the program, then used for loops to put it in the text area. Now, I want to take input from the text field, add that to the arraylist, and display the entire array, including the new element added. I tried using a for loop again, but when i click "add" while running, the program just freezes and nothing happens. Any suggestions?
Thanks.
private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {
// Using a for loop to display unsorted list, sorting the list, then using a for loop again to display the sorted list
String strUnsortedList = "";
for(int i = 0; i < strCDNames.size(); i++) {
strUnsortedList += strCDNames.get(i) + "\n";
}
Collections.sort(strCDNames);
String strSortedList = "";
for(int i = 0; i < strCDNames.size(); i++) {
strSortedList += strCDNames.get(i) + "\n";
}
txtOutput.setText("Unsorted Order: \n" + strUnsortedList + "\nSorted Order: \n" + strSortedList);
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
String strAddedList = "";
for (int i = 0; i < strCDNames.size(); i++) {
strAddedList += strCDNames.add(txtInputTitleArtist.getText());
}
txtOutput.setText(" " + strAddedList);
}
for (int i = 0; i < strCDNames.size(); i++) {
strAddedList += strCDNames.add(txtInputTitleArtist.getText());
}
This is an infinite loop. You keep adding to the list, which means that the list size will keep increasing. Hence i will always be lesser than strCDNames.size().
Instead you can do something like this:
strCDNames.add(txtInputTitleArtist.getText());
String strAddedList = String.join(" ", strCDNames);
Vivin is right. I just want to add that the arraylist add method returns a boolean (https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-). So, in this case strAddedList wouldn't even be properly updated.

Categories

Resources