2015-11-02 76 views
1

我刚刚得到了一些家庭作业,让我做这个奇怪的任务。老师希望我们将各种句子分解成单词。老师已将这些文件放入通过扫描仪导入的文件中。如何将字符串拆分为字符而不使用拆分方法或使用数组?

老师要我们然后用这句话,来计算长度,单词的数量应与词的数量沿着循环的每个迭代增加。

文件总是以“#”字符结束,因此这正是我开始。

这里是我迄今为止现在

class Assignmentfive 
    { 
private static final String String = null; 

public static void main(String[] args) throws FileNotFoundException 
{ 
    Scanner scan = new Scanner(new File("asgn5data.txt")); 

    String fileRead = " "; 
    System.out.print(fileRead); 
    double educationLevel = 0; 
    double wordCount = 0; 

    while (fileRead != "#") 
    { 
    fileRead = scan.nextLine();  

    int firstIndex = fileRead.indexOf(" "); 
    String strA = fileRead.substring(0,firstIndex); 
    System.out.print(strA); 
    int strLength = strA.length(); 
    wordCount++; 
    } 

,有更多的底部,也就是我的计算,我无法弄清楚如何从文件

任意抽取一个字一个字提示?

Thanks``

+0

你在正确的轨道上。你只需要用'fileRead'来做更多的事情。在找到一行中的第一个单词后,您需要在同一行中检查更多内容。 – Cruncher

+2

'FILEREAD = “#”' - > [?我如何在Java中比较字符串(http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo

回答

0

决不测试String平等==(这是参考身份,不与Object类型的价值认同你想.equals)。您可以使用Scanner(String)构造函数构造一个新的Scanner产生从指定字符串扫描的值。另外,你永远不close D本Scanner(由File的支持,这是一个资源泄漏)。您可以明确地致电close,但我更喜欢try-with-resources Statement。喜欢的东西,

try (Scanner scan = new Scanner(new File("asgn5data.txt"))) { 
    int wordCount = 0; 
    while (true) { 
    String fileRead = scan.nextLine(); 
    if (fileRead.equals("#")) { 
     break; 
    } 
    Scanner wordScanner = new Scanner(fileRead); 
    while (wordScanner.hasNext()) { 
     String word = wordScanner.next(); 
     System.out.println(word); 
     int wordLength = word.length(); 
     wordCount++; 
    } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

喜人!谢谢!是否有任何可能的方法让这个过程一次一行地完成?文件中有不同的行。 –

+0

@Jon这样做一次只能通过一行。然后一次一行地检查每行中的每个单词。 –

+0

是的,不过我一句一句地看着它,就像句子一样,得到所有的单词的平均长度,然后移动到第二句话,然后想法? –