简体   繁体   中英

Print two Arrays in java

I'm having problems printing these arrays. I get this error:

bad operand types for binary operator '+'. 

Not sure what am I missing. When I print only the first one it works fine but when I add the second doesn't work. What am I doing wrong? here is my code:

import javax.swing.JOptionPane;

public class testMenu {

public static void main(String[] args) {

String[] rieslingArray = {"Riesling","Dry","Off Dry", "Sweet"};
double[] rieslingPrice = {3.0,4.50,4.00,5.00};

JOptionPane.showMessageDialog(null, rieslingArray  + rieslingPrice);
}
}

You're making use of the binary + operator. Specifically, you're giving it two arguments of type String[] and double[] respectively. These types are not valid for the + operator.

You can try printing the second array with a second statement or concatenating the string representations of the two arrays and printing that string in a single statement. The following may be useful in getting the string representation of the arrays: Arrays.toString(array) .

Try this!

String[] rieslingArray = {"Riesling","Dry","Off Dry", "Sweet"};
double[] rieslingPrice = {3.0,4.50,4.00,5.00};

for (int i = 0; i < rieslingArray.length; i++) {

    JOptionPane.showMessageDialog(null, rieslingArray[i]  + rieslingPrice[i]);

}

Perhaps your confusion here is that you want to map the arrays together element-for-element. Since you're just trying to make a message display on screen, iterating through each array and getting each corresponding element works just fine.

import javax.swing.JOptionPane;

public class TestMenu {

    public static void main(String[] args) {

        String[] rieslingArray = {"Riesling", "Dry", "Off Dry", "Sweet"};
        double[] rieslingPrice = {3.0, 4.50, 4.00, 5.00};

        StringBuilder messageBuilder = new StringBuilder();
        for (int i = 0; i < rieslingArray.length; i++) {
            messageBuilder.append(rieslingArray[i] + ": " + rieslingPrice[i] + "\n");
        }
        String message = messageBuilder.toString();
        JOptionPane.showMessageDialog(null, message);

    }
}

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