2013-10-07 56 views
0

我遇到此問題從一個類獲取文件輸入並在另一個類中使用它。所以會發生什麼是我有一個名爲readFile.java的文件,讀取一個txt文件的行。我有另一個文件用於評估我想要使用文件輸入的堆棧。總而言之,我試圖找到一種方法,使用readFile.java的文件輸入來替換我的evalStack.java文件中的testInput字符串。在java中的不同類中使用txt文件輸入

這裏是readFile.java:

import java.util.Scanner; 

import java.io.*; 

public class readFile { 
    String fname; 

    public readFile() { 
     System.out.println("Constructor"); 
     getFileName(); 
     readFileContents(); 
    } 

    public void readFileContents() 
    { 
     boolean looping; 
     DataInputStream in; 
     String line; 
     int j, len; 
     char ch; 

     /* Read input from file and process. */ 
     try { 
      in = new DataInputStream(new FileInputStream(fname)); 

      looping = true; 
      while(looping) { 
       /* Get a line of input from the file. */ 
       if (null == (line = in.readLine())) { 
        looping = false; 
        /* Close and free up system resource. */ 
        in.close(); 
       } 
       else { 
        System.out.println("line = "+line); 
        j = 0; 
        len = line.length(); 
        for(j=0;j<len;j++){ 
         System.out.println("line["+j+"] = "+line.charAt(j)); 
        } 
       } 
      } /* End while. */ 

     } /* End try. */ 

     catch(IOException e) { 
      System.out.println("Error " + e); 
     } /* End catch. */ 
    } 

    public void getFileName() 
    { 
     Scanner in = new Scanner(System.in); 

     System.out.println("Enter file name please."); 
     fname = in.nextLine(); 
     System.out.println("You entered "+fname); 
    } 
} 

這是evalStack.java:

import java.util.Scanner; 
import java.io.*; 

public class evalStack { 

    static String testInput = "(6+3) + (3-2)"; 
    //This is the line I want to replace with the input the readFile gives me. 

    public static void main(String[] args){ 

     int maxLength = testInput.length(); 
     stackOb eval = new stackOb(maxLength); 
     boolean test = false; 

     //Evaluate and check parenthesis 
     for(int i = 0; i < testInput.length(); i++) 
     { 
      char a = testInput.charAt(i); 

      if(a=='(') 
      { 
       eval.push(a); 
      } 
      else if(a==')') 
      { 
       if(eval.empty() == false) 
       { 
        eval.pop(); 
       } 
       else 
       { 
        test = true; 
        System.out.println("The equation is a not valid one."); 
        System.exit(0); 
       } 
      } 
      else 
      { 
       continue; 
      } 
     } 
     if(eval.empty() == true && test == false) 
     { 
      System.out.println("The equation is a valid one."); 
     } 
     else 
     { 
      System.out.println("The equation is a not valid one."); 
     } 
    } 

回答

0
  1. import readFile;添加到evalStack.java
  2. 更改輸入的頂部:static String testInput = new readFile().readFileContents();
  3. 更改退貨類型:public String readFileContents()
  4. 更換j = 0;return line;

這將使評估第一線。

相關問題