My code works except I have to make it pass some Junit test. It passes all but one. It passes when the character enters nothing, enters upper case, lower case, or a mix of the two, and it works when the enter Hello World!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] textArray = new int[26];
System.out.print("Enter text: ");
readText(input, textArray);
}
public static void readText(Scanner input, int[]text){
char letter = 0;
if (input.hasNext() == false) {
System.out.println();
}
else {
while (input.hasNext()) {
String a = input.nextLine();
for (int i = 0; i < a.length(); i++) {
letter = a.charAt(i);
if (letter >= 'A' && letter <= 'Z') {
text[letter-65] = (text[letter-65]) + 1;
}
else if (letter >= 'a' && letter <= 'z') {
text[(letter - 32) - 65] = (text[(letter - 32) - 65]) + 1;
}
else if (letter == ' ') {
System.out.print("");
}
else {
System.out.print("");
}
}
}
}
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for (int y = 0; y < text.length; y++) {
if (text[y] > 0) {
System.out.println(alphabet[y] + ": " + text[y]);
}
}
}
The Junit tests this input: 1 2 3%n! ? >%n:) !!%n
The expected output is
Enter text:
//empty line here
But instead the output from my code is
Enter text: //with no line after
I'm not sure how to get the extra line after without ruining my other junit tests. I tried one way and it worked but then my Hello World didn't work properly.
And example of when its working:
When I hit run the console will say
Enter text:
I have a Scanner input so the user will enter some words and it will look like this in console
Enter text: sOme wordS
Then it will count the number of times each letter was used and print that to console like this
Enter text: sOme wordS
D: 1
E: 1
M: 1
O: 2
R: 1
S: 2
W: 1
If I don't enter anything when asked and just hit the enter key the output is
Enter text:
//empty line here
But when I enter
Enter text: 1 2 3
? ! >
:) !!
The output doesn't add an extra line at the end.
System.out.println("Enter text: " + "\n");You want a new line after "Enter text". If you also want to tab it, you can useSystem.out.println("Enter text: " + "\n\t");Enter text: //empty line here