I have 3 files, "MyFile" , "myOtherFile" , "yetAnotherFile" that my code will be drawing words from to put them in an array, check to see if they start with an uppercase, and if they do, it will also sort them alphabetically. all 3 have 3 or more words, one has only one word that starts with a lowercase so I can test that invalid input print line
I am somehow getting all 3 to print the invalid line
Added a counter so if counter > 0 it then does the print statement
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class StringSorter {
private String inputFileName;
//private String line;
public StringSorter(String fileName) {
inputFileName = fileName;
}
public void sortStrings() throws IOException {
FileReader input = new FileReader(inputFileName);
BufferedReader myReader = new BufferedReader(input);
String line, data = "";
String[] words;
int posCount = 0;
while ((line = myReader.readLine()) != null)
data += line;
words = data.split(",");
for(int posi = 0; posi < words.length; posi++) {
if(!Character.isUpperCase(words[posi].charAt(0))) {
posCount++;
}
}
if(posCount > 0) {
System.out.print("Invalid input. Word found which does not start with an uppercase letter.");
}
else {
for (int k = 0; k < words.length; k++) {
for (int i = k - 1; i >= 0; i--) {
if (words[i].charAt(0) < words[k].charAt(0)) {
String temp = words[k];
words[k] = words[i];
words[i] = temp;
k = i;
}
}
}
for(int print = 0; print < words.length - 1; print++){
System.out.print(words[print].trim() + ", ");
}
System.out.print(words[words.length-1]);
}
input.close();
myReader.close();
}
}
import java.io.*;
public class TestStringSorter {
public static void main(String[] args) throws IOException {
StringSorter sorterA = new StringSorter("MyFile.txt");
sorterA.sortStrings();
StringSorter sorterB = new StringSorter("myOtherFile.txt");
sorterB.sortStrings();
StringSorter sorterC = new StringSorter("yetAnotherFile.txt");
sorterC.sortStrings();
}
}
Invalid input. Word found which does not start with an uppercase letter.
Invalid input. Word found which does not start with an uppercase letter. Invalid input. Word found which does not start with an uppercase letter.