Adding to an ArrayList using input from GUI - java

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.

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.

How do I add an integer to an integer ArrayList in a GUI?

I am trying to add the Integer inputted by the user to the ArrayList. It's originally a String, so I converted it to an Integer. I added the Integer to the Arraylist, but now I'm not sure how to display it. I want to be able to keep adding marks, and have all the marks displayed on the screen. I tried a for loop, but I'm not sure what the second parameter would be.
Edit: for (i=0; ... ; i++) -- What would go in the second place?
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
String strInputMark;
int intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.parseInt(strInputMark);
ArrayList<Integer> Marks = new ArrayList<>();
int intMarks;
Marks.add(intInputMark);
}
Try this for loop:
String output = "";
for(int i = 0; i < Marks.size(); i++){
output += "\n"+Marks.get(i);
}
JOptionPane.showMessageDialog(null, output);
The short answer is i < Marks.size()
for (int i = 0; i < Marks.size(); i++) {
System.out.println(Marks.get(i));
}
You can try this
String strInputMark;
Integer intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.valueOf(strInputMark);
ArrayList<Integer> Marks = new ArrayList <>();
int intMarks;
Marks.add(intInputMark);
I think the answer is two-fold. First, you need to move 'Marks' outside of the method scope so it can be accessible and continually appended two as input continues. Second, as #Umesh said, Marks.size() will give you the total number of elements in your arraylist.

How to make a String contain each item in an ArrayList? (JAVA)

I have a String named listOfItemsBanned, and an ArrayList named itemsBanned.
Let's say the ArrayList itemsBanned contains 3 things: TNT, EnderPearl, and Sand.
I would want the String to be "TNT, EnderPearl, Sand".
And when something is removed from itemsBanned, it would remove it from the string, too.
So.. I want to be able to get every item included in an ArrayList and put it into one String with each item separated by commas.
You need only one line:
String listOfItemsBanned = itemsBanned.toString().replaceAll("^.|.$", "");
toString() of List produces a CSV of the elements, but wrapped in [ and ]. The call to replaceAll() removes the first and last characters to leave just the elements.
You could do this:
String listOfItemsBanned = "";
for(int i = 0; i < itemsBanned.size(); i++){ //loop threw contents of itemsBanned (List<String>)
String s = itemsBanned.get(i); //get the string in itemsBanned (i)
listOfItemsBanned = listOfItemsBanned + "," + s; //add s to listOfItemsBanned
}
Now, if you would like to get all of the items that are banned from the string listOfItemsBanned, you could do:
String[] s = listOfItemsBanned.split(",");
//start the for loop at 1 because when saved it will be ",TnT,Sand,Enderpearl", notice the extra , in the begining
for(int i = 1; i < s.size(); i++){ //loop threw all of the items banned.
String itmBanned = s[i];
}
You could now do anything with itmBanned, like convert it to a Material:
Material m = Material.getMaterial(itmBanned);
So, you could do something like this for a remove method:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.remove(type); //remove 'type' from the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
and for adding:
public void remove(String type){
String listOfItemsBanned = "";
itemsBanned.add(type); //add 'type' to the array
for(int i = 0; i < itemsBanned.size(); i++){
String s = itemsBanned.get(i);
listOfItemsBanned = listOfItemsBanned + "," + s; //reset the string to the new list
}
}
then you could check if the player is using a banned item, and cancel the event if they do, an example if they're using a banned block, like sand or TnT would be:
#EventHandler
public void playerInteract(PlayerInteractEvent e){
if(e.getAction.equals(Action.RIGHT_CLICK_AIR) || e.getAction.equals(Action.RIGHT_CLICK_BLOCK){
//the user has right-clicked
Material m = e.getItemInHand().getType(); //get the item in the user's hand
if(m != null){ //check that it's not null
if(listOfItemsBanned.contains(m.getName()){ //if listOfItemsBanned has the name of the item in the player's hand in it
e.setCanceled(true); //cancel the block place
}
}
}
}
Imports:
import java.util.Arrays;
import java.util.List;
Code:
public static void main(String args[]) {
String[] listOfItemsBanned = { "TNT", "EnderPearl", "Sand" }; // ArrayList
// of
// banned
// items
String output = ""; // Creates output String
for (int i = 0; i < listOfItemsBanned.length; i++) { // Loops through
// all items in
// the ArrayList
output += listOfItemsBanned[i]; // Adds item to String
if (i != listOfItemsBanned.length - 1) { // If it is not the last
// item in the ArrayList
// add ", "
output += ", ";
}
}
System.out.println(output); // Output String
}
Output:
TNT, EnderPearl, Sand

Delete Method without Array List

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.

Categories

Resources