如何从 java 中同一包中的另一个 class 访问变量

How to Access variable from another class in same package in java

我想在 class newrepeatedcount 中访问 class Totalnoofwords。 我想用

打印 class Totalnoofwords 的 "a"
System.out.println("( "+file1.getName() +" )-" +"Total words counted:"+total);

在 class newrepeatedcount 中。

所以我可以 运行 获取 System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);

的代码

这是我想要的 1 个输出的片段 ( filenameBlog 39.txt )-总字数=83,总重复字数counted:4

欢迎任何建议。 我是 java 的初学者。 下面是我的两个 class 代码。:)

Totalnoofwords.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.apache.commons.io.FileUtils;

  public class Totalnoofwords
  {
   public static void main(String[] args) 
  {
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };

    File folder = new File("E:\testfolder");
    File[] listOfFiles = folder.listFiles(filter);

    for (int i = 0; i < listOfFiles.length; i++) {
        File file1 = listOfFiles[i];
        try {
    String content = FileUtils.readFileToString(file1);

    } catch (IOException e) {
    e.printStackTrace();
        }
                BufferedReader ins = null;
        try {
            ins = new BufferedReader (
                    new InputStreamReader(
                        new FileInputStream(file1)));
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        String line = "", str = "";
        int a = 0;
        int b = 0;
        try {
                    while ((line = ins.readLine()) != null) {
    str += line + " ";
    b++;
    }
        } catch (IOException e) {
    e.printStackTrace();
    }
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreTokens()) {
        String s = st.nextToken();
        a++;
        }
               System.out.println(" Total no of words=" + a );
    }
        }
      }

newrepeatedcount.java

package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class newrepeatedcount  {
public static void main(String[] args){

FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };
    File folder = new File("E:\testfolder\");
    File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
        File file1 = listOfFiles[i];
        try {
                String content = FileUtils.readFileToString(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        BufferedReader ins = null;
        try {
                    ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    String st = null;
try {
    st = IOUtils.toString(ins);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 //split text to array of words
 String[] words=st.split("\s");
//frequency array
 int[] fr=new int[words.length];
//init frequency array
 for(int i1=0;i1<fr.length;i1++)
   fr[i1]=-1;
 //count words frequency
 for(int i1=0;i1<words.length;i1++){
   for(int j=0;j<words.length;j++){
     if(words[i1].equals(words[j]))
       {
         fr[i1]++;

            }
        }
 }      
 //clean duplicates
   for(int i1=0;i1<words.length;i1++){
     for(int j=0;j<words.length;j++){
       if(words[i1].equals(words[j]))
       {
         if(i1!=j) words[i1]="";
       }
 }
 }   
//show the output
int total=0;
//System.out.println("Duplicate words:");
for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
}
}
//System.out.println("Total words counted: "+total);    
//System.out.println("Total no of repeated words : "+total+" ");
System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total);
}  

}}

我试着把这两个代码放在一个单一的 class 但没有一个变量起作用 System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);

当我 运行 时,"a" 或 "total" 都不起作用。(反之亦然)如果我更改代码(可变)顺序。

谁能告诉我应该如何获得两个变量输出?? :)

这是我更新的 code.below。

 package ramki;
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FilenameFilter;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.util.StringTokenizer;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 public class newrepeatedcount  {
 public static void main(String[] args){
 FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };
    File folder = new File("E:\testfolder\");
    File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
        File file1 = listOfFiles[i];
        try {
                String content = FileUtils.readFileToString(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        BufferedReader ins = null;
        try {
                    ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
      String line = "", str = "";
      String st = null;
        try {
    st = IOUtils.toString(ins);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
   //split text to array of words
   String[] words=st.split("\s");
   //frequency array
   int[] fr=new int[words.length];
  //init frequency array
  for(int i1=0;i1<fr.length;i1++)
   fr[i1]=-1;
  //count words frequency
  for(int i1=0;i1<words.length;i1++){
   for(int j=0;j<words.length;j++){
     if(words[i1].equals(words[j]))
       {
         fr[i1]++;       
            }
        }
   }      
   //clean duplicates
    for(int i1=0;i1<words.length;i1++){
     for(int j=0;j<words.length;j++){
       if(words[i1].equals(words[j]))
       {
         if(i1!=j) words[i1]="";
       }
    }
   }    
     int a = 0;
    try {
    while ((line = ins.readLine()) != null) {
    str += line + " ";
    }   
} catch (IOException e) {
            e.printStackTrace();
}
StringTokenizer st1 = new StringTokenizer(str);
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
a++;
}
int total=0;
   for(int i1=0;i1<words.length;i1++){
if(words[i1]!=""){
//System.out.println(words[i1]+"="+fr[i1]);
total+=fr[i1];
} 
}
 System.out.println("( "+file1.getName() +" )-" +"Total repeated words counted:"+total+","+"total no of words:"+a);
// System.out.println("total no of words:"+a);
}
}}

无法从其他class访问主函数中的变量。 所以你可以修改 Totalnoofwords.java 类似的东西。

package Packagename;

public class Totalnoofwords
{

    static int a = 1;
        public void somename(){
            Totalnoofwords A=new Totalnoofwords();
            A.a+=5;
            System.out.println("a"+A.a);
        }

}

你的newrepeatedcount.java就像

package Packagename;

public class newrepeatedcount {

    public static void main(String[] args){
        Totalnoofwords B=new Totalnoofwords();
        B.somename();
        System.out.println("a:"+B.a);
    }

}

看起来你在同一个包中有 2 个主要方法,我不确定你是否想要这样,但这不会起作用,因为你没有 重载 方法。例如,目前你有一个 public static void main(String[] args) class,如果你改变另一个 class 接受一个额外的参数 public static void main (字符串[] args1,字符串[] args2)。

此外,为了访问您的第二个 class,如上所述,您将使用

Totalnoofwords totalNoofWords = new Totalnoofwords();
totalNoofWords.accessSomething();

但这行不通,因为您没有构造函数

package Packagename;

public class newrepeatedcount {

public static void main(String[] args){
    Totalnoofwords B=new Totalnoofwords();
    B.somename();
    System.out.println("a:"+B.a);
}

}