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));
}
Related
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.
I am a true beginner to programming, so forgive me.
I have a String Array filled with a set of quotes that I have a method randomly picking one to display on the screen. This all works perfectly, I'd like to take the next step now. I would like to have the ability to add text to this array that a user inputs on an Activity that I have created. I understand that Arrays are Immutable, but I am failing to figure out how to create an ArrayList, pre-fill it with my 50ish quotes and then have the ability to add more through the app later.
Here is the code I currently have...
public class FactBook {
public String[] mFacts = {
"Quote 1.",
"Quote 2.", };
public String getFact() {
String fact = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFacts.length);
fact = mFacts[randomNumber];
return fact;
}
References
ArrayList
Arrays
import java.util.ArrayList;
import java.util.Arrays;
public class FactBook {
// Public data members are not recommended.
// Make it at least protected and arrange controlled access to it
// by specific methods
public ArrayList<String> mFacts =
new ArrayList<String>(
Arrays.asList("Quote 1.", "Quote 2.")
)
};
public String getFact() {
String fact = "";
// Do you need to create a new Random every time?
// Perhaps creating it only once and storing it in a static
// (class wide) data member will be just as good: create it once,
// reuse it later.
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFacts.size());
fact = mFacts.get(randomNumber);
return fact;
}
// how to add
public void add(String newQuip) {
// Don't accept null or "all-white character" quotes
if(null!=newQuip && newQuip.trim().length()>0) {
this.mFacts.add(newQuip);
}
}
}
Look at Arrays class.
It has a helper method exactly for those cases:
List<String> facts = Arrays.asList("string1", "string2", ...);
Here's a simple method that pre-populates an ArrayList with your values, and then allows you to add more values to it later on
private ArrayList<String> createPrePopulatedList() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Quote 1.");
///Add any more you want to prepopulate like this
return arrayList;
}
You can call this method like so.
private ArrayList<String> myArrayList = createPrepopulatedList();
Now you can simply add whatever you want to it dynamically with add().
You should probably do some reading on Java data structures before you jump into Android programming. Here's some help with ArrayList https://www.tutorialspoint.com/java/java_arraylist_class.htm
Edit
Many users are commenting that the Class Word is useless, which is probably true in this case. The reason I added it, is because I need it later on in the program.
This program has 3 classes - WordList, Word and a test class. I'm trying to get the method 'readBook' to read through a file, and send every word over to the method 'addWord'. Method addWord will check if the ArrayList allWords contains that word. If it doesn't, addWord will then add the word to an array, aswell as to send it over to class Word. When I run the program, nothing happens. I tried to print out allWords.size(), which returned 0.
Class WordList:
public class WordList {
String nextWord;
ArrayList<String> allWords = new ArrayList<String>();
public void readBook (String filename) throws Exception{
File file = new File(filename); //File has one word on each line.
Scanner innFile = new Scanner(file);
for (int i = 0; i<file.length(); i++){
if(innFile.hasNextLine()){
nextWord = innFile.nextLine();
addWord(nextWord);
}
}
}
private void addWord(String word){
for (String check : allWords){
if (!check.equalsIgnoreCase(word)){
allWords.add(word);
new Word(word);
}
else if(check.equalsIgnoreCase(word)){
System.out.println("The word allready exsist.");
}
else{
System.out.println("Something went wrong.");
}
}
}
Class Word:
public class Word {
String word;
ArrayList<String> allWords = new ArrayList<String>();
Word(String text){
word = text;
allWords.add(word);
System.out.print(allWords);
}
The test class:
public class TestClass {
public static void main (String[] args) throws Exception{
WordList list = new WordList();
list.readBook("path.../scarlet.text");
WordList newList = new WordList();
System.out.println(newList.numberOfWords());//A method printing out allWords.size()
}
}
You are populating allWords list of WordList class inside for (String check : allWords). Initially it would be empty hence it will never enter the for loop and allWords will never get populated. In turn new Word(word) will not be called and allWords of word class will be empty.
You have two issues with your code.
First, when that main loop (for (String check : allWords)) runs, allWords is going to be empty. Therefore, you will never add any elements to it, and that means it will always have a size of 0. To correct this, you probably need to add a boolean variable that gets set to true if you find the word. Then, after the loop, if the boolean variable is still false, add the word to the list.
Secondly, you've got allWords defined on two places: in your WordList class, and in your Word class. The WordList.allWords array is being updated correctly (as far as I can tell, once you fix the above mentioned issue). However, the Word.allWords array is not doing anything other than storing a single String value... twice (once in the array, once in a variable). The Word class isn't really doing anything useful, so I would opt to get rid of it.
I would get rid of the Word class completely, since it's currently not doing anything other than storing a String, which you could do with a String variable.
When the method addWord(String) is called it never enters the for loop because allWords is initially an empty ArrayList. Your call to "new Word(String)" is never reached.
I don't think you need allWords in both the Word class and the WordList class (?)
If you're just trying to get the unique words you can do this:
Set<String> words = new LinkedHashSet<>();
File file = new File("some file");
Scanner inFile = new Scanner(file);
for (int i = 0; i < file.length(); i++)
if (inFile.hasNextLine())
words.add(inFile.nextLine());
inFile.close();
then call
words.size()
to check if an array list contains a certain string you can use a for loop.
I'm not sure if this is the best way to go about it, but it should work.
for(int i = 0; i<yourArrayList.size(); i++){
if (yourArrayList.get(i).!contains(yourString)){
yourArrayList.add(yourString);
}
In test class try:
public static void main(String[] agrs) throws Exception {
WordList w = new WordList();
w.readBook("pathToMyFile"); // This way you access to readBook method
....
}
And add the word in method addWord when attribute allWords is empty.
private void addWord(String word){
if (allWords.isEmpty()) {
allWords.add(word);
} else {
// Your code
}
}
I'm making a quiz like game. I have two arrays (One with the states and the other with the capitals). Basically it asks the user what capital goes with a random state. I want that if the user inputs the correct state for it to be like nice job or whatever but I do not know how to compare the user input to the specific array compartment. I tried .contains but no avail...
Any help?
My bad - I'm using Java
For Example
if(guess.equals(capitals[random]))
where guess is the string and capitals is the array and random is the random number
Basically you want a mapping String -> String (State -> Capital). This could be done using a Map<String, String> or by creating a State class which will contains its name and its capital as attributes.
But to my mind, the best option is to use an enum as you know that there is 50 states. Here's a small example.
public class Test {
static final State[] states = State.values();
static Random r = new Random();
static Scanner sc = new Scanner(System.in);
public static void main (String[] args){
State random = states[r.nextInt(states.length)];
random.askQuestion();
String answer = sc.nextLine();
if(answer.equals(random.getCapital())){
System.out.println("Congrats");
} else {
System.out.println("Not really");
}
}
}
enum State {
//Some states, add the other ones
ALABAMA("Montgomery"),
ALASKA("Juneau");
private final String capital;
private State(String capital){
this.capital = capital;
}
public String getCapital(){
return this.capital;
}
public void askQuestion(){
System.out.println("What capital goes with "+this.name()+"?");
}
}
Logic similar to this should work. You want to save the user input to a String variable, and then compare it to an n sized array.
for(int i=0; i<arrayName.length();i++)
{
if(userinputString.equalsIgnorCase(arrayName[i])
{
System.out.println("HUrray!");
}//end if
}//end for
Ok so you are somehow producing a random number, and then need to compare the input to the String in the capital Array for that random number/
Im assuming the arrays are ordered such that capitals[10] gives you the capital for states[10].
If so, just save the index to a variable.
int ranNum=RandomNumFunction();
Then just see if
if(capitals[ranNum].equalsIgnoreCase(userInput))
//do something
This might be a dumb question but its frustrating me. I am adding into my array list a object during a loop but outside of the loop, all of the array list is overwritten with the last element in the array. It goes something like this.
while(fin.hasNextLine())
{
String line = fin.nextLine();
String[] user = line.split(",");
r.add(new User(user[0], user[1]));
System.out.println(r.get(count).getName());
count++;
}
This gives me an output of something like this (USER1, USER2, USER3, etc.) during the loop.
However, right after the loop I now have an output of something like this (USER500, USER500, USER500).
while(fin.hasNextLine())
{
String line = fin.nextLine();
String[] user = line.split(",");
r.add(new User(user[0], user[1]));
System.out.println(r.get(count).getName());
count++;
}
for (int i =0; i < r.size(); i++)
{
System.out.println(r.get(i).getName());
}
I managed to verify that this is the class where I'm having the problem and only one other method uses the array list in this class which i commented out.
I'm going to have to put on my psychic debugging goggles, but I predict tht your User class looks like this:
public class User {
private static String name;
public User(String x, String somethingElse) {
name = x;
}
public String getName() {
return name;
}
}
Note that name is static. Therefore that's one variable - not one per instance of User. You want it to be an instance field, so that each User object has a different name variable.