My code is relatively simple. I have to create a program that takes the input of a string, and tracks the frequency of each string. As well as the user should be able to type in a line, click enter and be able to enter the next line, etc. until the user clicks enter twice in a row. Here is my code so far:
package javaapplication8;
import java.util.Scanner;
public class JavaApplication8 {
static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
System.out.print("Enter a sentence: ");
String input = sc.nextLine() ;
while (input!=null) {
if (input.isEmpty()){
System.out.println("Read Enter Key.");
break;
} else if (sc.hasNextLine()){
input = sc.nextLine();
} else {
input = null;
}
}
String sentence = input.replaceAll("\\W", "");
sentence = sentence.toUpperCase();
int [] frequencies = new int [26];
int value = 65;
double valuecount = 0;
for (int i = 0; i < 26 ; i++) {
for (int i2 = 0; i2 < sentence.length(); i2++){
if (sentence.charAt(i2) == value){
valuecount += 1 ;
}
}
double percent = (valuecount / sentence.length() ) * 100;
char val = (char) value;
System.out.format (val + " occured %.2f percent of the time. \n", + percent);
value += 1;
valuecount =0 ;
}
}
}
Netbeans isn't giving me any syntax errors meaning there isn't any exception stack trace. I'm guessing the issue is between the replaceAll line and the null statements in my while loop (that allows the user to click the enter key twice before the program runs.
I'm very new to Java, so sorry for any 'rookie mistakes'
Thanks!
Edit: My apologies, I thought the exception stack trace was the red text you get when you run your program with syntax errors (missing a semicolon, etc.)
I mean that my program runs, but it gives me NaN instead of the percentage amount, but when I remove the whole while loop, the program works perfectly without the next line feature.