Why does JOptionPane disturb my string?
I have a line of code similar to the following:
final String food =
(String) JOptionPane.showInputDialog(this, "Choose a food", "Food",
JOptionPane.QUESTION_MESSAGE, null,
{"Pizza", "Hot Dog"}, "Pizza");
When I use the variable food
, I get a part of the string, but also some other characters that I can't see. I am not sure what is going on. Can someone help me?
To reproduce the problem:
System.out.println(System.getenv("APPDATA") + File.separ开发者_如何学Goator + food + ".txt");
It is supposed to print something like this:
C:\Users\userName\AppData\Roaming\Pizza.txt
But it actually gives the output:
.txtsers\userName\AppData\Roaming\Pizza
The error must be somewhere else in your code.
I just ran the following code:
String[] options = {"Pizza", "Hot Dog"};
final String food = (String) JOptionPane.showInputDialog(null, "Choose a food", "Food", JOptionPane.QUESTION_MESSAGE, null, options, "Pizza");
System.out.println("'" + food + "'");
When I selected Pizza I got Pizza at the console. When I selected Hot Dog I got Hot Dog.
About the other part of your code. I just ran:
String[] options = {"Pizza", "Hot Dog"};
final String food = (String) JOptionPane.showInputDialog(null, "Choose a food", "Food", JOptionPane.QUESTION_MESSAGE, null, options, "Pizza");
StringBuilder sb = new StringBuilder();
sb.append(System.getenv("APPDATA"));
sb.append(File.separator);
sb.append(food);
sb.append(".txt");
System.out.println(sb.toString());
And got C:\some folder at my computer\Hot Dog.txt and C:\some folder at my computer\Pizza.txt.
Your code doesn't even compile because it expects an Object[]. try new String[] {"Pizza", "Hot Dog"} instead of just {"Pizza", "Hot Dog"}
Some Glassball guessing:
The output of .txtsers\userName\AppData\Roaming\Pizza
looks like there was a carriage-return in your string (before the .txt
). You can reproduce this with this code:
System.out.println("C:\\users\\userName\\AppData\\Roaming\\Pizza\r.txt");
The question would be how this carriage return got into your string. Obviously, the code you've shown in the question does not produce it.
Create a short self contained compilable example (SSCCE), and you either will find the reason on the way, or we can show you, when you post it here (add it to the question).
精彩评论