[英]How do i change my code so that if theres a second input it will add onto my histogram?
public class Histogram {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
String lettersInput = input.nextLine();
lettersInput=lettersInput.toLowerCase();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int[] count = new int[alphabet.length()];
for(int x = 0; x < lettersInput.length();x++){
int letter = alphabet.indexOf(lettersInput.charAt(x));
if(letter < 0){
continue;
}
count[letter]++;
}
for(int x = 0; x < count.length; x++){
System.out.print(String.format("%s" + ":" +"%s", alphabet.charAt(x), new String(new char[count[x]]).replace('\0','*')));
System.out.println();
if(count[x]< 1) {
continue;
}
}
}
}
現在它只接受一個字母輸入,如果你想輸入另一組,它會創建一個新的直方圖。
一個簡單的解決方案:創建一個像makeHistogram()這樣的方法,它接受一個字符串並為此打印直方圖(基本上,您只需將一些代碼從 main 方法移動到該新方法中)。
然后在 main 方法中放入一個 while 循環。 在該循環的主體內,您首先要求用戶輸入另一行文本,然后調用新方法並將該輸入傳遞給它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.