How do I make this program work correctly - java

In this program, I am supposed to check if each word in the file "Paper" is in the file "dictionary". If the word is not in the file dictionary, it prints out ("Line #" "the word"). The problem in this code is the loop. I don't know to make the loop reset.
EX: a dictionary file has two words big and small
a paper file has a sentence his foot is small
The program will print
Line: 1: his
Line: 1: foot
Line: 1: is
import java.util.Scanner;
import java.io.*;
public class SpellCheck{
public static void main(String[] arg) throws FileNotFoundException{
Scanner readfile = new Scanner(new File("paper"));
String word = "";
int count = 0;
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Scanner openDictionary = new Scanner(new File("Dictionary"));
String wordInDictionary = openDictionary.next();
if(word.equals(wordInDictionary)){
}else{
System.out.println("Line " + count + ": " + word);
openDictionary.close();
}
}
}

I would rather preprocess dictionary file.
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Just like you have written here, make a hashset or whatever the container you'd like and copy over words in dictionary file. And, using another loop to do your task (check if the container contains the word you just read.) In this way, two loop are not nested so it will run O(n).

Related

How to store each word from a scanner to an array

I wan't to use the scanner to ask for input a few words and am expecting a delimiter ", " to separate each word.
I then want to split each word and store it in an array so I could use it for other purposes i.e, instantiate an object with an array argument for my constructor.
Could someone help me please
Update: I have resolved the problem! Thanks everyone for the suggestions.
If I understand your question correctly, this is that I would do
Scanner keyb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = keyb.nextLine();
String[] stringArray = input.split(",");
To see the results:
for(int i=0; i < stringArray.length; i++){
System.out.println(i + ": " + stringArray[i]);
}
This will work for any size sentence as long as each word is separated by a ,.
import java.util.*;
public class testing {
public static void main (String[] args) {
String splitter = ",";
Scanner scanner = new Scanner(System.in);
System.out.println("user input:");
String[] fewwords = scanner.nextLine().split(splitter);
System.out.println(fewwords[0] + fewwords[1] + fewwords[2]);
}
}
You can do this using a loop and checking with Scanner.hasNext(). Like so:
Scanner k = new Scanner(new File("input.txt"));
k.useDelimiter(",");
LinkedList<String> words = new LinkedList<String>();
while(k.hasNext()){
words.add(k.next());
}
System.out.println(words);
Notice how I set the delimiter to be a comma, so that each next read word is distinguished as being separated by commas.

homework parsing strings: removing comma from string (java zybooks)

I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];

How to index a line of text in Java?

I'm very new to the Java language, and in one of my school assignments, they want us to take in a simple text file that contains a line of text and index it (so that it can be used as a decoder for a secret message). I already know how to read the file and get that line of text into the program, but how do I index each character in the line of text and assign each character a value starting at 0 and ending at the length of the line of text? Here is what I have so far (*Note: I was trying different stuff with the code in the for loop, so I'm not sure if I'm on the right track or not):
import java.util.*;
import java.io.*;
public class Decoder
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
String fileName;
System.out.println("Please enter the name of a file to be decoded: ");
fileName = keyboard.nextLine();
File testFile = new File(fileName);
Scanner inputFile = new Scanner(testFile);
String keyPhrase = inputFile.nextLine();
for(int i = 0; i < keyPhrase.length(); i++)
{
char letter = keyPhrase.charAt(i);
int num = (int)letter;
System.out.println(num);
}
}
}

Line/Token based processing (java)

I'm writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an "#" symbol, it means that one of the teams is playing at home. I'm trying to count the lines that contain an "#" and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here's the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
input1.nextLine();
} else{
input1.nextLine();
}
}
System.out.println("Number of games with a home team: " + count);
}
Your line variable always has the first line's value. You should set line in the loop, something like that.
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
line = input1.nextLine();
} else{
line = input1.nextLine();
}
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = null;
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
line = input1.nextLine();
if(line.contains("#")){
count++;
}
}
System.out.println("Number of games with a home team: " + count);}

For loop iterating through string and adding/replacing characters

I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.

Categories

Resources