简体   繁体   中英

How can I create a program that stores a numerous amount of names/numbers in an array by clicking a button without the method resetting my counter?

public void actionPerformed(ActionEvent e)
{
  int clicked = 0;
 if(arg == "Enter")
 {
     clicked++;
 }

 if (clicked == 0)
{
names[0] = nameField.getText();
numbers[0] = numberField.getText();
}

if( clicked == 1)
{
names[1] = nameField.getText();
numbers[1] = numberField.getText();
}

 if(arg == "Print")
 {
   String name = nameField.getText();
   String number = numberField.getText();
   JOptionPane.showMessageDialog(null,names[0] + numbers[0] + names[1] + numbers[1] + numbers[2] + names[2],"Info",JOptionPane.INFORMATION_MESSAGE);
 }

My program must take multiple names and numbers and be able to enter them into an array. After all of the data is entered, it must be able to be printed. I am having trouble under the Enter method because it continues to reset everytime instead of remaining constant. It only allows me to print the last typed name/number instead of saving all of the content. I am unsure of how to fix this and would be grateful for any suggestions at this point.

You could start by moving int clicked out of this function.

Right now your actionPerformed function each time its called reset your clicked to 0 since you are setting it to 0 at the beggining of it.

public void actionPerformed(ActionEvent e)
{
    int clicked = 0;   //HERE is your problem
    if(arg == "Enter");
    ...

Making it a variable of class instead of function should help.

EDIT: You can do something like this:

int clicked = 0 
public void actionPerformed(ActionEvent e)
{
    if(arg == "Enter"){
         names[clicked] = nameField.getText();
         numbers[clicked] = numberField.getText();
         clicked++;
    }

As it was mentioned you could also use List , since it would save problems if you don't know how big of an array u need.

List<String> names = new ArrayList<String>();
List<String> numbers = new ArrayList<String>();

And in use

    if(arg == "Enter"){
         names.add(nameField.getText());
         numbers.add(numberField.getText());
    }

Instead of an array, you could use an ArrayList , it will allow you to add elements without having to supply an index.

Without givening away too much, like this:

ArrayList<String> names = new ArrayList<String>();
...
names.add("Johnny"); // Adds to the end of the list
names.add("Frank");

That way you don't need to keep the 'clicked' count.

You can use .get(i) to get the element at index i . Or just loop over the entire list using a for each loop:

for(String name : names) { // i.e. for each 'name' in 'names'
    System.out.println(name);
    // Or do something else with 'name'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM