如何使用java构造函数显示数据? 公共类演示2{ 私有静态最终字符串=null; 静态字符串st; 静态字符串[]拆分; 静态int C=0; public demo2()引发FileNotFoundException{ 试一试{ File File=新文件(“/home/madhu/demo1.txt”); 扫描仪sc=新扫描仪(文件); while(sc.hasNextLine()){ st=sc.nextLine(); C++; //System.out.println(st=sc.nextLine()); 字符串[]split=st.split(“,”); 对于(int i=0;i

如何使用java构造函数显示数据? 公共类演示2{ 私有静态最终字符串=null; 静态字符串st; 静态字符串[]拆分; 静态int C=0; public demo2()引发FileNotFoundException{ 试一试{ File File=新文件(“/home/madhu/demo1.txt”); 扫描仪sc=新扫描仪(文件); while(sc.hasNextLine()){ st=sc.nextLine(); C++; //System.out.println(st=sc.nextLine()); 字符串[]split=st.split(“,”); 对于(int i=0;i,java,eclipse,Java,Eclipse,如何在构造函数示例中读取和打印文件 public class demo2 { private static final String String = null; static String st; static String[] split; static int C = 0; public demo2() throws FileNotFoundException { try { File file = new File("/home/madhu/demo1

如何在构造函数示例中读取和打印文件

public class demo2 {
private static final String String = null;
static String st;
static String[] split;
static int C = 0;

public demo2() throws FileNotFoundException {
    try {
        File file = new File("/home/madhu/demo1.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            st = sc.nextLine();
            C++;
            //System.out.println(st =sc.nextLine());
            String[] split = st.split(",");
            for (int i = 0; i < split.length; i++) {
                // System.out.println(split[i]);
            }

        }
        System.out.println(C);
    } catch (NumberFormatException e) {
        System.out.println(e);
    }

}
public static void main(String[] args) throws FileNotFoundException {
    demo2 obj = new demo2();
    for(int i =0;i<2;i++) {
    System.out.println("Splitted values are :"+obj.st);
    }
}

您在主函数的循环中打印了两次相同的值。您能解释一下为什么需要不同的值吗?
private static final String String=null;
-什么?OP似乎想要打印他们从文件中读取的每一行,而不是最后一行中的每一个字段,这就是您的答案。我是getting编译错误为:表达式的类型必须是数组类型,但解析为Stringconfirm,请检查我的示例“C:/Users/func/Desktop/Unsafe/src/main/resources/input.txt”@А峈峈峈峈峈峈峈峈峈峈峈峈23
public class App {

    public App() throws FileNotFoundException {
        Scanner scanner = new Scanner(new File(absolute path src));
        while (scanner.hasNextLine())
            System.out.println(scanner.nextLine());
    }

    public static void main(String[] args) throws FileNotFoundException {
        new App();
    }
}