我正在制作一个程序来计算用户输入字符串中字母的频率,并且最近遇到了“算术异常”错误。
我不能为我的生活找出导致它的原因,即使我知道这是因为某事被划分为0。
这是我的代码:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
我知道我现在只有ABC和M,但是后来会有人工作。
这是我第一次在这里发帖,我仍然对Java很新,所以非常感谢任何帮助!
答案 0 :(得分:1)
我跑了它,它说第67行。这是总数:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
修复:
double occ = (number > 0) ? number/input * 10 : 0;
如果数字设置为0,则将occ设置为0.祝你好运。 希望这会有所帮助。
答案 1 :(得分:1)
导致错误的代码行在您的方法中:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
{class}}变量在您的班级中声明:
input
由于您没有初始化它,也没有在代码中更改值,因此Line 6: public static int input;
的值在整个程序中保持为0。 (未初始化的int变量的默认值为0)
由于它始终为0,因此您始终将数字除以0。
input