0

とにかく、カウントを変数に入れることができるものはありますか?たとえば、行数をカウントするためのカウントがあります。その後、カウントが提供する数値を使用し、この数値を別の場所で使用できる変数に追加します。たとえば、別の数値を追加したり、パーセンテージを見つけたり、数値を使用して円グラフを作成したりします。

public void TotalCount12() throws FileNotFoundException  {
        Scanner file = new Scanner(new File("read.txt"));
        int count = 0;
        while(file.hasNext()){
            count++;
            file.nextLine();
            }
        System.out.println(count);
        file.close();

カウントする数値を使用して、別の場所(別の方法など)で使用したいのですが、その方法がわかりません。

ありがとうございました。

4

3 に答える 3

1

プログラミングに慣れていない場合は、まずこのjavatutorialを完了することをお勧めします。

クラス内でメソッド外のグローバル変数として (クラスの属性として)定義すると、クラス内のすべてのメソッドで使用できます。

しかし、異なるクラス内のプロジェクトのあらゆる場所でそれを使用することについて質問がある場合は、シングルトン デザイン パターンを使用できます。

public class ClassicSingleton { 
    private static ClassicSingleton instance = null; 
    protected ClassicSingleton() {
     // Exists only to defeat instantiation. 
    } 
    public static ClassicSingleton getInstance() {
        if(instance == null) 
        {
            instance = new ClassicSingleton(); 
        } 
        return instance; 
    }
}
于 2013-03-01T14:18:35.553 に答える
0

編集変数 のゲッターメソッドを作成しcountます。

例えば

public class Test {
  private int count = 0;

  public void method1(){
    while(file.hasNext()){
        count++;
        file.nextLine();
        }
    System.out.println(count);
  }

  public void method2(){
    System.out.println(count);
  }

  public int getCount(){
    return count;
  }
}
于 2013-03-01T14:09:20.357 に答える
0

作成したメソッドで値を返すだけです。

public class Test {

  public int TotalCount12() throws FileNotFoundException  {
    Scanner file = new Scanner(new File("read.txt"));
    int count = 0;
    while(file.hasNext()) {
      count++;
      file.nextLine();
    }
    System.out.println(count);
    file.close();
    return count;
  }

  public static void main(String[] args) {
    Test t = new Test();
    int testCount = TotalCount12();
  }

}
于 2013-03-01T15:25:02.887 に答える