Identify words with ascending characters from text file

Posted by user2914000 on Stack Overflow See other posts from Stack Overflow or by user2914000
Published on 2013-10-24T03:43:25Z Indexed on 2013/10/24 3:54 UTC
Read the original article Hit count: 99

Filed under:
|
|

I am having a fair amount of trouble trying to write a program that counts the amount of ascending words (words in which each character is larger than the previous character) in a text file. I have tried a few different methods to solve this but cannot seem to get it working.

If anyone could help me revise the code to work properly it would be appreciated. The code will print about 5 of the words from the list of nearly 20000, but none considered are ascending (the file does have many ascending words) and it sometimes prints the same word twice.

I am printing theWord to the console simply to see if the code works.

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

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

String theWord;
Scanner inputFile = new Scanner(new File("file.txt"));
boolean ascending = true;
int i = 1;

while(inputFile.hasNextLine()){
  theWord = inputFile.nextLine();

  if(theWord.length() >= 2){
    while(i < theWord.length() - 1){
      if(theWord.charAt(i) <= theWord.charAt(i + 1)){
        ascending = true;
        System.out.println("+ " + theWord);
        totalNum = totalNum + 1;
      }
      else{
       ascending = false;
       System.out.println("= " + theWord);
      }
      i++;
    }
  }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about loops