I have file of which I need to read input. On one of the lines, there is no name added. In this case, I want to print out that no match was found. The problem that I'm having is that I don't know how I can make sure the program actually reads the part as an empty string. What happens now is that the will just leave the line empty on the console.
The date input looks like this:
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
2=30=15=8=4=3=2=0=0=0;
class Administration {
public static final int TOTAL_NUMBER_OF_SIMULARITY_SCORES = 10;
public static final String ZERO_MATCHES = "_";
public static final String LESS_THAN_TWENTY_MATCHES= "-";
public static final String TWENTY_OR_MORE_MATCHES = "^";
PrintStream out;
Administration() {
out = new PrintStream(System.out);
}
void printSimilarityScores (Scanner similarityScoresScanner, String similarityScoresInput) {
similarityScoresScanner.useDelimiter("=|;");
int length = similarityScoresInput.length();
for (int i = 0; i < TOTAL_NUMBER_OF_SIMULARITY_SCORES; i++) {
int grade = similarityScoresScanner.nextInt();
if (grade == 0) {
out.printf(ZERO_MATCHES);
} else if (grade < 20) {
out.printf(LESS_THAN_TWENTY_MATCHES);
} else {
out.printf(TWENTY_OR_MORE_MATCHES);
}
}
System.out.print("\n");
similarityScoresScanner.useDelimiter(";|,");
while(similarityScoresScanner.hasNext()) {
String name = similarityScoresScanner.next();
if (length < 22) {
out.printf("No matches found\n");
} else {
System.out.print("\n" + name);
}
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
while (fileScanner.hasNext()) {
String finalGradeInput = fileScanner.nextLine();
String similarityScoresInput = fileScanner.nextLine();
Scanner finalGradeInputScanner = new Scanner(finalGradeInput);
Scanner similarityScoresScanner = new Scanner(similarityScoresInput);
printFinalGrade(finalGradeInputScanner);
printSimilarityScores(similarityScoresScanner, similarityScoresInput);
}
}
public static void main(String[] argv) {
new Administration().start();
}
}
An easier solution would be to read the file, line by line and handle them like this :
split by the separator
check if there is more than 1 element,
if positive print them
Scanner similarityScoresScanner = new Scanner(myFile);
while (similarityScoresScanner.hasNextLine()) {
String[] content = similarityScoresScanner.nextLine().split("[;,]");
if (content.length == 1) {
System.out.println("No matches found");
} else {
for (int i = 1; i < content.length; i++) {
System.out.println(content[i]);
}
}
}
Related
So I am trying to create a program which takes a text file, creates an index (by line numbers) for all the words in the file and writes the index into the output file. Here is the main class:
import java.util.Scanner;
import java.io.*;
public class IndexMaker
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
String fileName;
// Open input file:
if (args.length > 0)
fileName = args[0];
else
{
System.out.print("\nEnter input file name: ");
fileName = keyboard.nextLine().trim();
}
BufferedReader inputFile =
new BufferedReader(new FileReader(fileName), 1024);
// Create output file:
if (args.length > 1)
fileName = args[1];
else
{
System.out.print("\nEnter output file name: ");
fileName = keyboard.nextLine().trim();
}
PrintWriter outputFile =
new PrintWriter(new FileWriter(fileName));
// Create index:
DocumentIndex index = new DocumentIndex();
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
lineNum++;
index.addAllWords(line, lineNum);
}
// Save index:
for (IndexEntry entry : index)
outputFile.println(entry);
// Finish:
inputFile.close();
outputFile.close();
keyboard.close();
System.out.println("Done.");
}
}
The program contains two more classes: IndexEntry which represents one index entry, and the DocumentIndex class which represents the entire index for a document: the list of all its index entries. The index entries should always be arranged in alphabetical order. So the implementation for these two classes are shown below
import java.util.ArrayList;
public class IndexEntry {
private String word;
private ArrayList<Integer> numsList;
public IndexEntry(String w) {
word = w.toUpperCase();
numsList = new ArrayList<Integer>();
}
public void add(int num) {
if (!numsList.contains(num)) {
numsList.add(num);
}
}
public String getWord() {
return word;
}
public String toString() {
String result = word + " ";
for (int i=0; i<numsList.size(); i++) {
if (i == 0) {
result += numsList.get(i);
} else {
result += ", " + numsList.get(i);
}
}
return result;
}
}
import java.util.ArrayList;
public class DocumentIndex extends ArrayList<IndexEntry> {
public DocumentIndex() {
super();
}
public DocumentIndex(int c) {
super(c);
}
public void addWord(String word, int num) {
super.get(foundOrInserted(word)).add(num);
}
private int foundOrInserted(String word) {
int result = 0;
for (int i=0; i<super.size(); i++) {
String w = super.get(i).getWord();
if (word.equalsIgnoreCase(w)) {
result = i;
} else if (w.compareTo(word) > 0) {
super.add(i, new IndexEntry(w));
result = i;
}
}
return result;
}
public void addAllWords(String str, int num) {
String[] arr = str.split("[^A-Za-z]+");
for (int i=0; i<arr.length; i++) {
if (arr[i].length() > 0 ) {
addWord(arr[i], num);
}
}
}
}
When I run this program I'm getting an error and I'm not sure where the error came from.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at DocumentIndex.addWord(DocumentIndex.java:14)
at DocumentIndex.addAllWords(DocumentIndex.java:35)
at Main.main(Main.java:53)```
There is where the problem arises:
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
lineNum++;
index.addAllWords(line, lineNum);
}
You add lineNum by 1 before executing the line after. At the last loop, lineNum will be 1 more than the maximum, because the loop starts at line 1, and it is 0 index based.
Instead, use:
String line;
int lineNum = 0;
while ((line = inputFile.readLine()) != null)
{
index.addAllWords(line, lineNum);
lineNum++;
}
I have a program that takes in a file of unindented code and comments the program takes the specified file and will output an indented version of the code.
I keep on getting the java.lang.ArrayIndexOutOfBoundsException: 1 error. This seems to occur when I have only one comment on a line as for when it splits the string the index only takes up 0. I have got an if statement in place to handle a comment on a line on its own but it still throws the exception.
Would I need to implement an if statement to check whether or not the split string has more than 1 part to it?
import java.io.*;
import java.util.*;
class Program
{
public static int spaces = 0;
public static int longestLine = 0;
public static int commentSpaces;
public static String beforeComment;
public static String afterComment;
public static void main(String args[]) throws FileNotFoundException
{
Scanner input2 = new Scanner(new File("C:\\Users\\James\\Music\\code.java")); //get text from file
while (input2.hasNextLine() == true) { //get the longest line
String text = input2.nextLine();
if (text.contains("//")) {
if (text.contains("\"//")) {
printLine(text);
}
String[] parts = text.split("//");
String codeOnly = parts[0];
if (codeOnly.length() > longestLine) {
longestLine = codeOnly.length();
}
}
else {
if (text.length() > longestLine) {
longestLine = text.length();
}
}
if (input2.hasNextLine() == false) {
break;
}
}
Scanner input3 = new Scanner(new File("C:\\Users\\James\\Music\\code.java"));
while (input3.hasNextLine()) { //indent comments
String text = input3.nextLine();
if (text.contains("}")) {
spaces -=2;
}
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
if (text.startsWith("//")){
String justComment = text;
commentSpaces = longestLine - spaces + 6;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(justComment);
System.out.println(" ");
}
if (text.contains("\"//")) {
printLine(text);
}
if (text.contains("//")) {
String[] parts = text.split("(?=//)");
beforeComment = parts[0].trim(); // trim() to get rid of any spaces that are already present within the code
afterComment = parts[1];
printLine(beforeComment);
commentSpaces = longestLine - beforeComment.length() - spaces + 5;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(afterComment);
System.out.println();
}
else {
printLine(text);
System.out.println();
}
if (text.contains("{")) {
spaces +=2;
}
}
}
public static void printLine(String text) {
Scanner data = new Scanner(text);
while (data.hasNext()) {
System.out.print(" " + data.next());
}
}
public static void yesItContains() {
System.out.print("It contains a string");
System.exit(0);
}
}
I think that if text is "something//" meaning it is ending in a empty comment your parts will only have length 1. So yes, you need to check it, e.g. via afterComment = parts.length > 1 ? parts[1] : "";. Note that lines like "something // something else // blabla" might break that logic as well.
I've been stuck on this problem for a few days and can't find any answers to this question. It's slowly driving me insane. I need to make a two methods, one that add that word to the Array Word[] words and one that removes it if the word occurs more than once. Sadly, every time I try to use .add or anything of the sort it doesn't work. I am so confused.
WordBagClient
public class WordBagClient {
public static void main(String[] args) throws IOException {
System.out.println("PMJ's WordBagClient ...");
String filename;
if(args.length > 0) { // Use run-time first argument value
filename = args[0];
}
else { // Prompt user to enter name of data file and store response
System.out.print("Enter name of input file:");
Scanner keyboard = new Scanner(System.in);
filename = keyboard.nextLine();
}
// Establish Scanner object that can read from the input data file.
Scanner input = new Scanner(new File(filename));
WordBag wordBag = new WordBag(256);
String s;
// Add each of the words until a blank line is encountered
do {
s = input.nextLine();
System.out.println(s);
if(s.length() > 0) {
addTask(s,wordBag);
}
} while (s.length() > 0);
printWordBag(wordBag);
// Remove an instance of each of the words until a second blank line is encountered
do {
s = input.nextLine();
System.out.println(s);
if(s.length() > 0) {
//removeTask(s,wordBag);
}
} while (s.length() > 0);
printWordBag(wordBag);
}
static void addTask(String s, WordBag wordBag) {
Scanner wordScanner = new Scanner(s);
while(wordScanner.hasNext()) {
String string = wordScanner.next();
String word = Word.wordOf(string);
wordBag.add(new Word(word));
}
}
static void removeTask(String s, WordBag wordBag) {
Scanner wordScanner = new Scanner(s);
while(wordScanner.hasNext()) {
String string = wordScanner.next();
String word = Word.wordOf(string);
Word object = new Word(word);
while(wordBag.multiplicityOf(object) > 0) {
wordBag.remove(object);
}
}
}
static void printWordBag(WordBag wordBag) {
System.out.println("The word bag now contains:");
System.out.println("--------------------------");
System.out.println(wordBag.toString());
System.out.println("--------------------------");
/*
wordBag.reset();
while(wordBag.hasNext()) {
System.out.print(wordBag.next());
if(wordBag.hasNext()) { System.out.print(","); }
}
System.out.println("\n"+"--------------------------");
*/
}
}
This is my WordBag.java
public class WordBag {
public static final int DEFAULT_CAPACITY = 8; //Default number of distince words
//allowed in a bag.
private int capacity; //The capacity of this instance's private arrays
private Word[] words; //The array to hold the words
private int[] counts; //The array to hold the corresponding counts
private int nextIndex; //Indicates the next available element position
public WordBag() {
this.words = new Word[DEFAULT_CAPACITY];
this.counts = new int[DEFAULT_CAPACITY];
}
public WordBag(int specifiedCapacity) {
if (capacity>-1){
this.capacity = specifiedCapacity;
this.words = new Word[capacity];
this.counts = new int[capacity];
}else{
this.capacity = DEFAULT_CAPACITY;
this.words = new Word[DEFAULT_CAPACITY];
this.counts = new int[DEFAULT_CAPACITY];
}
nextIndex = 0;
}
public boolean has(Word word) {
boolean dog = false;
do{
if(words[nextIndex].equals(word)){
return dog = true;
}else{
nextIndex++;
}
}while(nextIndex<=capacity && words[nextIndex]!=word);
return dog;
}
public int multiplicityOf(Word word) { //Stub!!!
int result=0;
do{
words[nextIndex].equals(word);
result = result+1;
}while(nextIndex<=capacity && words[nextIndex]!=word);
return result;
}
public void add(Word word) { //Stub!!!
do{
words[nextIndex]=(word);
}while(nextIndex<=capacity && words[nextIndex]!=word);
nextIndex++;
}
public void remove(Word word) { //Stub!!!
do{
if(multiplicityOf(word)>0){
word=null;
}else{
word=word;
}
}
while(nextIndex<=capacity && words[nextIndex]!=word);
}
private final String COMMA = ",";
public String toString() { //Stub!!!
String result = "";
result = Arrays.toString(words);
return result;
}
}
This is my Word Class
public class Word {
public static final String SYMBOLS = "`~!##$%^&*()-_=+[{]}\\|;:'\",<.>/?";
private String word = "";
public Word(String string) {
String word = Word.wordOf(string);
if(Word.isWord(word)) {
this.word = word;
}
}
public String toString() {
return word;
}
public boolean equals(Word that) {
return this.compareTo(that) == 0;
}
public int compareTo(Word that) {
return this.toString().compareTo(that.toString());
}
public static String wordOf(String s) {
String result = "";
//Trim of leading and trailing whitespace
s = s.trim();
//Scan over leading symbols
int start;
for(start=0; (start<s.length()) && (SYMBOLS.indexOf(s.charAt(start))>=0); start++) {
}
//Scan over trailing symbols
int stop;
for(stop=s.length()-1; (stop > start) && (SYMBOLS.indexOf(s.charAt(stop))>=0); stop--) {
}
//Isolate what is left in the middle
if(start <= stop) {
result = s.substring(start,(stop+1));
}
//Return
return result;
}
public static boolean isWord(String s) {
s = s.trim();
return (s.length() > 0) && (s.equals(Word.wordOf(s)));
}
}
Here is my input file
So I am reading in a .txt file and I keep getting a string index out of bounds exception. I have been trying to find duplicate words and keep the array sorted as I add words to it. I thought my problem was trying to sort and search the array when It has no words or only one word in it.
The line with the ** in front of it is the problem line. Its line 129
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict
{
static String dict[] = new String[20];
static int index = 0;
public static void main(String args [])
{
readIn();
print();
}
public static void readIn()
{
File inFile = new File("carol.txt");
try
{
Scanner scan = new Scanner(inFile);
while(scan.hasNext())
{
String word = scan.next();
if(!Character.isUpperCase(word.charAt(0)))
{
checkRegex(word);
}
}
scan.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
public static void addToDict(String word)
{
if(index == dict.length)
{
String newAr[] = new String[dict.length*2];
for(int i = 0; i < index; i++)
{
newAr[i] = dict[i];
}
if(dict.length < 2)
{
newAr[index] = word;
index++;
}
else
{
bubbleSort(word);
if(!wordHasDuplicate(word))
{
newAr[index] = word;
index++;
}
}
dict = newAr;
}
else
{
dict[index] = word;
index++;
}
}
public static void checkRegex(String word)
{
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if(!regexMatcher.find())
{
addToDict(word);
}
}
public static void print()
{
try
{
FileWriter outFile = new FileWriter("dict.txt");
for(int i = 0; i < index; i++)
{
outFile.write(dict[i]);
outFile.write(" \n ");
}
outFile.close();
}
catch (IOException e)
{
System.out.println("Error ");
}
}
public static void bubbleSort(String word)
{
boolean swap = true;
String temp;
int wordBeforeIndex = 0;
String wordBefore;
while(swap)
{
swap = false;
wordBefore = dict[wordBeforeIndex];
for(int i = 0; (i < word.length()) && (i < wordBefore.length()) i++)
{
**if(word.charAt(i) < wordBefore.charAt(i))**
{
temp = wordBefore;
dict[wordBeforeIndex] = word;
dict[wordBeforeIndex++] = temp;
wordBeforeIndex++;
swap = true;
}
}
}
}
public static boolean wordHasDuplicate(String word)
{
int low = 0;
int high = dict.length - 1;
int mid = low + (high - low) /2;
while (low <= high && dict[mid] != word)
{
if (word.compareTo(dict[mid]) < 0)
{
low = mid + 1;
}
else
{
high = mid + 1;
}
}
return true;
}
}
Error is shown below:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at BuildDict.bubbleSort(BuildDict.java:129)
at BuildDict.addToDict(BuildDict.java:60)
at BuildDict.checkRegex(BuildDict.java:90)
at BuildDict.readIn(BuildDict.java:30)
at BuildDict.main(BuildDict.java:14)
Check the length of wordBefore as a second condition of your for loop:
for(int i = 0; (i < word.length()) && (i < wordbefore.length()); i++)
I am getting a "No line found" exception when I run this. This is the only method in my project that gives me this error. Every other method uses the same code and parameters, but none of them encounter this error.
The method in question is findLargestPalindrome()
Exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at cs1410.TestClass.findLongestPalindrome(TestClass.java:51)
at cs1410.TestClass.main(TestClass.java:12)
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestClass
{
static Scanner test = new Scanner("Hello world! This is my program.");
public static void main(String[] args)
{
System.out.println(findLongestPalindrome(test));
}
public static boolean isPalindrome(String s)
{
if(s.length() == 0)
{
return false;
}
int stringLength = s.length() -1;
if(stringLength == 0)
{
return false;
}
for(int i = 0; i < stringLength; i++)
{
if(s.charAt(i) == s.charAt(stringLength))
{
stringLength--;
}
else
{
return false;
}
}
return true;
}
public static String findLongestPalindrome(Scanner s)
{
int pLength = 0;
String largestPalindrome = "";
String currentToken;
if(s.nextLine().length() > 0)
{
String input = s.nextLine();
StringTokenizer inputTokens = new StringTokenizer(input);
while(inputTokens.hasMoreTokens())
{
currentToken = inputTokens.nextToken();
if(isPalindrome(currentToken) == true)
{
if(currentToken.length() > pLength)
{
pLength = currentToken.length();
largestPalindrome = currentToken;
}
}
}
}
else
{
return null;
}
return largestPalindrome;
}
}
When you access the Scanner in findLongestPalindrom() you only have one line in the Scanner ("Hello world! This is my program.") and you are trying to read two lines (you discard the first line),
if(s.nextLine().length() > 0) // <-- reads the line and advances
{
String input = s.nextLine(); // <-- there isn't another line.
should be something like
String input = s.nextLine();
if (!input.isEmpty()) {
// ...
or
String input = s.nextLine();
if (input.length() > 0) {
// ...
Every time you call Scanner.nextLine() you consume the line.