Reputation: 49
This is a program that lets user input 6 random letters, and the program sorts these letters in order. Ex user inputs j, d, e, l, w, q and program outputs d, e, j, l, q, w.
Unfortunately the code freaks out and does not sort a thing. Note: I am using a GUI
Under public I created a class and an array to eventually house all inputted letters
class Abc {
String letter;
Abc (String _letter) {
letter = _letter;
}
}
ArrayList <Abc> alphabet = new ArrayList <Abc>(3); //note its 3, not 6 like in the example
After user types in a letter in a textField, they press the "addButton" which adds and saves the value in the array.
String letter = letterField.getText();
//Store values in array
Abc a = new Abc(letter);
alphabet.add(a);
Now for the actual 'sorting' part. Which takes place after user presses a "Play" button.
String[] abc = new String[3]; //LINE I FORGOT TO ADD
for (int k = 0; k < abc.length; k++) {
abc[k] = letterField.getText();
int x;
for (int i = 0; i < abc.length; i++) {
// Asume first value is x
x = i;
for (int j = i + 1; j < abc.length; j++) {
//find smallest value in array (random)
if (abc[j].compareToIgnoreCase(abc[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = abc[i];
abc[i] = abc[x];
abc[x] = temp;
}
textArea.append(abc[i] + "\n");// Output correct order
}
}
I had originally used this code to sort integers, the only difference between that program and this program is the int/String and this one I am currently working on allows the user to input the letters and the program does not randomize them like it did with the integer program.
I had thought this would be enough code to do the trick and organize some letters, but apparently not.
For the actually problem, when I input the letters and add them to the array and press "play" the program freaks and a lovely error pops up...
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "d"
Note: 'd' being the last letter I inputted for the last time I tested the program...all of five seconds ago.
Any hints or advice would be greatly appreciated!
Upvotes: 0
Views: 252
Reputation: 2672
You are probably using parseInt() or something similar in the part of the code, where you get input from user. That method should be off now, as you no longer want to change input from String to any number. By the way, just for information, class Arrays in java include some sorting methods. You can check those at this site
Upvotes: 0
Reputation: 178263
A NumberFormatException
is thrown when you attempt to parse some text into a number, but the text is not a number, such as in your example: "d"
.
You mentioned that you had this code working with integers, then converted it to work with letters. Most likely, you forgot to take out the code (which you haven't shown here) that parses the input into a number. You should take out that code and accept the user's input as text as originally inputted.
Upvotes: 1