I am new to JAVA. This is what I have to do:
User inputs as many marks as he wants by writing a number and pressing add button doing that over and over and all those marks are added in arraylist. After he is done, he presses the sort button and all the marks are sorted and displayed.
This is what I have:
ArrayList <Integer> marks=new ArrayList();
private void addActionPerformed(java.awt.event.ActionEvent evt) {
marks.add(Integer.parseInt(marksinput.getText()));
Collections.addAll(marks);
}
private void sortActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList <Integer> marks=new ArrayList();
marks.add(Integer.parseInt(marksinput.getText()));
Collections.addAll(marks);
Collections.sort(marks);
marksoutput.setText(marks + "\n");
}
The problem I am having is it does not display all the numbers I added before. It just displays the last number. Any help is appreciated and thank you in advance!
You need to push up the marks list at class level. Remember, variables created inside a method only have method scope.
//Move it outside of method at class level
ArrayList <Integer> marks=new ArrayList();
private void addActionPerformed(java.awt.event.ActionEvent evt) {
{
//Push the latest value into marks list, it will already contain all previous entries as we are not re initializing it.
marks.add(Integer.parseInt(marksinput.getText()));
}
private void sortActionPerformed(java.awt.event.ActionEvent evt) {
Collections.sort(marks);
marksoutput.setText(marks + "\n");
}
I am not sure where the events are actually saved; you are adding them to the marks array but that is local to the addActionPerformed method and lost once that is completed.
It is hard to say with just the code you posted but maybe you can try to make marks a global object in your class.
Related
so I have a recursive program where I am trying to generate all the permutations of a String. I intend to store the permutations in a list of list called ans.
Every single current permutation is stored in the container list which is used to populate the ans list. I am suspecting , since list is a reference type so maybe I am loosing the values in ans list because the container list is getting manipulated? Am I an idiot
import java.util.*;
public class practice_3 {
static String str="abc";
static List<List<Character>> ans=new ArrayList<List<Character>>();
public static void permString(ArrayList container )
{
if(container.size()==str.length())
{System.out.println(container);
ans.add(container);
return;
}
for(int i=0;i<str.length();i++)
{
if(!container.contains(str.charAt(i)))
{
container.add(str.charAt(i));
permString(container);
container.remove(container.size()-1);
}
}
}
public static void main(String[] args) {
ArrayList<Character> container=new ArrayList<>();
permString(container);
System.out.println(ans);
System.out.println("container end="+container);
}
}
You are correct, as container was passed by reference the changes made in container from point to point reflects within ans (Collection of Collection) as well.
To avoid this, you need to clone / create a new copy of the container at the time of storing into the ans collection. This can be easily achieved by following.
ans.add(new ArrayList<Character>(container));
I have a program that has a list of items.
I then search for a string and try to find it in said list.
What I would want to happen is: It finds the first occurrence, then prints it out or saves it somewhere so I can use it later (by highlighting user choice for example). Then once I search for the same string again it should return me the second occurrence, then the third, etc. When it doesn't find any more occurrences it should go back to the start and repeat it.
This is a crude example of what I have:
public static void main(String[] args) {
ArrayList<String> exampleList = new ArrayList<String>();
exampleList.add("string1");
exampleList.add("john");
exampleList.add("string2");
exampleList.add("arnold");
exampleList.add("string3");
String inputExample = "str"
for (String s : exampleList) {
if (s.contains(inputExample)) {
System.out.println(s);
break;
}
}
}
I added the break inside the if so I can get only the first result. If I remove it I will get all results.
In the program I have similar code associated to the click of a button, highlighting the user choice if the list contains what the user searched for, this is just an example.
What happens in my program is that only the first result will be highlighted (because I broke out of the loop) or only the last result will be highlighted (because I didn't break out of the loop).
How can I make it so the search picks up where it left off, officially ignoring the results it already obtained?
As #Alex pointed out in his answer you should use an iterator and save your results in a private ArrayList for furthure use of those search results.
If you are not familiar with the iterator use this
I have written a simple class HighlightingUserInput that behaves as your conditions. It gives the first search result and prints it and saves in a ArrayList, if you didn't exit the program(or you can add a search button, if user presses search again) then gives the second search result, etc.
Feel free to ask anything related to this following program.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class HighlightingUserInput{
private static ArrayList<String> resultsString=new ArrayList<>();
public static void main(String [] args) {
ArrayList<String > allStrings=new ArrayList<>();
allStrings.add("string1");
allStrings.add("john");
allStrings.add("string2");
allStrings.add("arnold");
allStrings.add("string3");
Scanner scanner=new Scanner(System.in);
CharSequence userIput=scanner.nextLine();
Iterator iterator = allStrings.iterator();
while(!scanner.nextLine().equals("exit")) {
inner:
while (iterator.hasNext()) {
String s = (String) iterator.next();
if (s.contains(userIput)) {
System.out.println(s);
HighlightingUserInput.resultsString.add(s);
break inner;
}
}
if(!iterator.hasNext())
iterator = allStrings.iterator();
}
}
}
You can loop through your list and each time you find the string you can call your method to highlight it. Alternatively, if you want to be able to get strings 1 by 1 each time you call your method, then you can use an iterator. On the first call to your method you obtain an iterator for your list and store it in a private field of your class. On subsequent calls you use this iterator to get the next matching string from your list.
public static void main(String[] args) {
ArrayList<String> exampleList = new ArrayList<String>();
exampleList.add("string1");
exampleList.add("john");
exampleList.add("string2");
exampleList.add("arnold");
exampleList.add("string3");
String inputExample = "str";
int count = 0;
while(count >= 0){
System.out.println(customSearch(exampleList, inputExample, count);
count ++;
} // write break statement when count reaches to a particular value based on your use case
String customSearch(List<String> words, String searchKey, int count){
List<String> searchedWords = words.stream().filter(word -> if word.toLowerCase().contains(searchKey.toLowerCase)).collect(Collectors.toList());
return searchWords.get(count%searchedWords.size());
This program is supposed to save the button value "ab" to the ArrayList whenever the button is pressed, but the if command seems to never work, I tried removing it and seeing if it works, it does and the ArrayList is updated with the new value. So if I pressed the button or not when it appears in the J Windows, nothing happens.
This program later on saves the array to a file, so basically nothing is saved if the if is there and I clicked as many times I wanted, but if the if loop in this one goes then it works
public void actionPerformed(ActionEvent a)
{
ArrayList<String> aList = new ArrayList<String>();
if (a.getActionCommand() == "ab")
aList.add("ab");
}
So if this was done it world print out and aList would be filled with ab in the zero index :
public void actionPerformed(ActionEvent a)
{
ArrayList<String> aList = new ArrayList<String>();
aList.add("ab");
}
Firstly, aList is local variable and it'll be removed on the exit of the method.
Secondly:
a.getActionCommand() == "ab"
You must compare String objects using equals method:
a.getActionCommand().equals("ab")
or
"ab".equals(a.getActionCommand()) //hack for prevention null reference after a.getActionCommand()
There is reference comparison in your example, but using equals you'll be compare objects, not references.
Your list only exists in the scope of the method. In order to work with it from the "outside" you should use it as a instance variable.
For example:
public class A implements ActionListener {
private final List<String> aList;
public A() {
aList = new ArrayList<String>();
}
...
public void actionPerformed(ActionEvent a)
{
if (a.getActionCommand().equals("ab")) {
aList.add("ab");
}
}
}
My problem is very simple but i can't find the way to solve it. Basically i want to create an Arraylist and add elements to it using a loop(up to as many elements as i want). i'm using the netbeans gui, and whenever i press a button "add" i want to add the string variables name and capital to my arraylist and display it in a TextArea.
something like:
[london, england,america,united states etc..]
so far the only thing it does is print the two variables name and capital many times like:
[londonn, england, london, england etc..]
here is the code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name, capital;
ArrayList<String> input = new ArrayList<>();
name = jTextField1.getText();
capital = jTextField2.getText();
for(int i=0;i < 10;i++) {
input.add(name);
input.add(capital);
jTextArea4.setText(String.valueOf(input));
}
}
If you're wanting your ArrayList to continually grow, then you need to make it a class variable and not a local variable to you jButton1ActionPerformed.
Also take out the for loop. When you're adding a new name and capital, to your ArrayList, you only have to do it once.
Something like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Make sure input is a class variable and it will continue to grow
input.add(jTextField1.getText());
input.add(jTextField2.getText());
jTextArea4.setText(String.valueOf(input));
}
Once your ArrayList is a class variable, you're going to want a way to either clear the ArrayList or remove items from it.
you have to remove the for loop becuase you are storing the same values more than one time.
you can do like this.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name, capital;
ArrayList<String> input = new ArrayList<>();
name = jTextField1.getText();
capital = jTextField2.getText();
input.add(name);
input.add(capital);
jTextArea4.setText(String.valueOf(input));
}
here are getting the name and capital values from the text fields and stroing in into the arraylist and then display the values of the arraylist in teh textfield4..
if you want to add as much elements you can do but when you are setting the jtextField4 you have to get the last element from the input arraylist becuause the arraylist object contains 10 stings.
like this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name, capital;
ArrayList<String> input = new ArrayList<>();
name = jTextField1.getText();
capital = jTextField2.getText();
for(int i=0;i < 10;i++) {
input.add(name);
input.add(capital);
jTextArea4.setText(String.valueOf(input.get(input.size)));
}
}
I hope this will help you.
try to move jTextArea4.setText(String.valueOf(input)) outside the for loop
You need to keep the following code outside the loop:
jTextArea4.setText(String.valueOf(input));
Completely remove the loop. And if you want that arraylist to be useful you must make it a class level variable
ArrayList<String> input = new ArrayList<>();
private void jButton1ActionPerformed(ActionEvent evt) {
String name, capital;
name = jTextField1.getText();
capital = jTextField2.getText();
input.add(name);
input.add(capital);
jTextArea4.setText(String.valueOf(input));
}
I'm trying to find a way to pick what an array stores based on which button the user presses on a GUI.
Obviously this will not compile due to the variable name being the same.
The calculations are performed outside of the loop but use "values". I just want the user to be able to determine what values are set in the array based on what button they press. The obvious issue is not being able to use the name "values" twice, which is where I am having a problem as I have a for loop that requires the variable "values" and I don't want to have to be re adding the code several times for each data set when there is most likely an easy workaround that I am currently not seeing.
Just pull the declaration out:
double[] Xvalues = null;
if (e.getSource() == X1btn) {
Xvalues = new double[]{2001,350,799,1004};
}
else if (e.getSource() == X2btn) {
Xvalues = new double[]{5,62,28,500};
}
A better approach would be to subclass JButton and associate a set of values with each instance. To retrieve the button's values, include an accessor.
Example
public final class JArrayButton extends JButton{
private final double[] values;
public JArrayButton(double[] values){
this.values = values;
}
// ... other stuff (e.g. constructors)
public final double[] getValues(){
return values;
}
}
What if you create the array ourside the loop.
double Xvalues[] = new Xvalues[5]; //or whatever size you want
and then use if/else statement
if (e.getSource() == X1btn) {
Xvalues ={2001,350,799,1004};
} else if (e.getSource() == X2btn) {
Xvalues={5,62,28,500};
}