3

我有一个任务,我有两个类,一个驱动程序类,它使用扫描仪实用程序从键盘读取字符串,然后记录它的字母频率。(每个字母在输入的字符串中出现多少次)。我的程序应该继续输入文本行,直到您连续键入两个 Returns。然后代码应该打印字母频率,然后是一个报告,给出最常见的字母及其计数(如果最常见的字母并列,任何最常见的字母都可以)。我的代码也忽略了字母大小写 - 所以应该计算大写字母和小写字母。

我的司机班是

import java.util.*;

public class LetterDriver{
  public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    String tScan = " ";
    while(tScan.length() > 0){
      tScan = s.nextLine();
    }
  }
}

我的实际个人资料课程是

public class LetterProfile {
  int score[] = new int [26];

 public void countChars (String s) {
    s.toLowerCase();
    char a = 'a';
    for (int i = 0; i < s.length(); i++) {
      int next = (int)s.charAt(i) - (int) a;
      if ( next<26 && next >= 0)
        score[next]++;
    }
 }

    public void scoreLine (String lines) {  // prints letter + # of appearance
      int index = lines.length();
      for (int j = 0; j<index; j++) {
        score[j]++;
        System.out.println(j + score[j]);
     }
 }

    public int largestLength() { // finds most frequent letter
      int largest = 0;
      int largestindex = 0;
      for(int a = 0; a<26; a++) 
        if(score[a]>largest){
        largest = score[a];
        largestindex = a;
      }
      return largestindex;

    }


    public void printResults() {
       largestLength();
      System.out.println(largestLength());
    }
  }

我的代码再次编译,当我运行它时,它允许我输入我的文本输入,但是当我返回两次时,我得到的只是空白输出。我认为这可能与我的配置文件类没有从我的驱动程序类中正确读取但无法找出问题所在有关。

4

4 回答 4

2

您只是在您的 main 方法中从扫描仪读取数据,您还没有在 Main 方法中实例化您的类 LetterProfile,所以它什么也不做。

于 2013-03-19T17:21:48.657 回答
1

您只是从 main 方法中的输入获取数据,您必须在静态 main 方法中实例化名为 LetterProfile 的第二个类,因此它什么也不做。java从读取静态变量开始,然后是静态方法,然后是其他的。

于 2013-03-19T17:42:59.100 回答
1

你在主类的哪里调用了 LetterProfile 的方法?

请参考以下代码:-

import java.util.*;

public class LetterDriver{
  public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    LetterProfile lp=new LetterProfile();
    String tScan = " ";
    while(tScan.length() > 0){
      tScan = s.nextLine();
    }
   lp._any_of_letter_profile_class_method();
  }
}

或者

public class LetterDriver{
  public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    LetterProfile lp=new LetterProfile();
    String tScan = " ";
    while(tScan.length() > 0){
      tScan = s.nextLine();
      lp._any_of_letter_profile_class_method();
    }

  }
}
于 2013-03-19T17:44:35.743 回答
1

您没有LetterProfile在任何地方使用课程!您只是在读取输入,但没有传递到LetterProfile. 在您的驱动程序中实例化LetterProfile类并调用相关方法。

您的驱动程序类可能如下所示:

public class LetterDriver{
  public static void main(String[] args){
    LetterProfile letterProfile = new LetterProfile();
    Scanner s = new Scanner(System.in);
    String tScan = " ";
    while(tScan.length() > 0){
      tScan = s.nextLine();
      letterProfile.countChars(tScan);
    }

    // Print the result
    letterProfile.printResults()
  }
}
于 2013-03-19T17:23:57.220 回答