2016-10-31 60 views
0

我嘗試創建的程序可以: 1.從文件中讀取字符 2.將這些字符添加到ArrayList中 3.檢查行內是否只有字符a,b,c(沒有其他的/無空格)Java - 從文件讀取字符到ArrayList

如果有3個是真實的 - 1.比較第一&最後一個字符的ArrayList,如果他們是不同打印 「OK」

示例文件: abbcb - OK abbca - NOT OK a bbc - NOT OK abdcb - NOT OK bbbca - OK

目前我:

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


public class Projekt3 
{ 
    public static void main(String[] args) throws IOException 
    { 
     List<String> Lista = new ArrayList<String>(); 
     Scanner sc = new Scanner(System.in).useDelimiter("\\s*"); 
     while (!sc.hasNext("z")) 
     { 
      char ch = sc.next().charAt(0); 
      Lista.add(ch); 

      //System.out.print("[" + ch + "] "); 

     } 
    } 

} 

我有添加字符列出的問題。我會很感激的幫助。

+0

爲什麼你認爲你將被允許一個'char'添加到'String'列表? – shmosel

+2

你的'List'需要一個'String'而不是'char'。將類型參數更改爲'Character',即'List ',如果您想要'char'的'List' –

回答

-1

我認爲這是良好的開端,您:

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

public class Project3 { 
public static void main(String[] args) { 
    String path = "/Users/David/sandbox/java/test.txt"; 

    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) { 

     String currentLine = null; 

     // Array list for your words 
     List<String> arrayList = new ArrayList<>(); 

     while ((currentLine = br.readLine()) != null) { 
      // only a, b and c 
      if (currentLine.contains("a") && currentLine.contains("b") && currentLine.contains("c")) { 
       // start character equal end character 
       if (currentLine.substring(0, 1) 
         .equals(currentLine.substring(currentLine.length()-1, currentLine.length()))) { 
        arrayList.add(currentLine); 
        System.out.println(currentLine); 
       } 
      } 
     } 
    } catch (Throwable e) { 
     System.err.println("error on read file " + e.getMessage()); 
     e.printStackTrace(); 
    } 
} 
} 
0
import java.io.*; 
import java.util.ArrayList; 

public class Project3 { 

public static void main(String[] args) throws FileNotFoundException, IOException { 

    BufferedReader reader = new BufferedReader(new FileReader("//home//azeez//Documents//sample")); //replace with your file path 
    ArrayList<String> wordList = new ArrayList<>(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     wordList.add(line); 
    } 

    for (String word : wordList) { 
     if (word.matches("^[abc]+$")) { 
      if (word.charAt(0) == word.charAt(word.length() - 1)) { 
       System.out.print(word + "-NOT OK" + " "); 
      } else { 
       System.out.print(word + "-OK" + " "); 
       } 
      } 
     } 
    } 
}