I have written a spellchecker program that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. The program should write the incorrect words to a file and I have received an error message on lines 57-58, saying "type mismatch between void to String" and when I ran it on eclipse, I got an unresolved compilation problem" error. What am I doing wrong so it can run smoothly on both Eclipse & on the command line? Here's the code:
import java.util.*;
import java.io.*;
public class SpellChecker {
public static void readDict(){
File file = new File ("words.txt");
ArrayList <String> array = new ArrayList <String> ();
try{
Scanner input = new Scanner (file).useDelimiter("[A-Za-z]");
while (input.hasNext()){
String line = input.nextLine();
String [] wordArray = line.split(" ");
for(String str : wordArray){
array.add(str);
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("File is not found.");
System.exit(1);
}
return;
}
public static void readFile(){
File file = new File ("mary.txt");
String [] array;
String [] array2 = null;
try{
Scanner input = new Scanner (file);
int i = 0;
array = new String [10];
while(i < array.length && input.hasNext()){
String story = input.nextLine();
String[] storyarray = story.split(" ");
array2[i] = storyarray[i];
i++;
for(i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
input.close();
}
}
catch(FileNotFoundException e){
System.out.println("File cannot be found.");
System.exit(1);
}
}
public static void main(String[] args) {
args[0] = readDict();
args[1] = readFile();
if(args == 4){
System.out.println(args[0]);
System.out.println(args[1]);
}
}
public static Scanner input = new Scanner(System.in);
}
Related
I am trying to create an implementation that reads a file that the user has typed and submitted. The code for that is located in the SetTester class (shown below). In my implementation I already have an array declared called String[] myArray = new String [] {}; to hold the data from the file. How would I be able to take the file that is being called in the tester class and put it into that array?
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}
For reading from a file I use this class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
then in the class main you can add this code and you edit the path so you can read a file an get an array out of it
public static void main(String args[]) throws IOException {
ReadFile r = new ReadFile("here you put the path that the user provide");
String[] text = r.OpenFile();
ArrayList<String> array = new ArrayList<>();
array.addAll(Arrays.asList(text));
}
If you have any questions let me know!
I am writing code that reads in a text file through the command line arguments in the main method and prints out each word in it on its own line without printing any word more than once, it will not print anything, can anyone help?
import java.util.*;
import java.io.*;
public class Tokenization {
public static void main(String[] args) throws Exception{
String x = "";
String y = "";
File file = new File(args[0]);
Scanner s = new Scanner(file);
String [] words = null;
while (s.hasNext()){
x = s.nextLine();
}
words = x.split("\\p{Punct}");
String [] moreWords = null;
for (int i = 0; i < words.length;i++){
y = y + " " + words[i];
}
moreWords = y.split("\\s+");
String [] unique = unique(moreWords);
for (int i = 0;i<unique.length;i++){
System.out.println(unique[i]);
}
s.close();
}
public static String[] unique (String [] s) {
String [] uniques = new String[s.length];
for (int i = 0; i < s.length;i++){
for(int j = i + 1; j < s.length;j++){
if (!s[i].equalsIgnoreCase(s[j])){
uniques[i] = s[i];
}
}
}
return uniques;
}
}
You have several problems:
you're reading whole file line by line, but assign only last line to variable x
you're doing 2 splits, both on regexp, it is enough 1
in unique - you're filling only some parts of array, other parts are null
Here is shorter version of what you need:
import java.io.File;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Tokenization {
public static void main(String[] args) throws Exception {
Set<String> words = new HashSet<String>();
try {
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String[] lineWords = scanner.nextLine().split("[\\p{Punct}\\s]+");
for (String s : lineWords)
words.add(s.toLowerCase());
}
scanner.close();
} catch (Exception e) {
System.out.println("Cannot read file [" + e.getMessage() + "]");
System.exit(1);
}
for (String s : words)
System.out.println(s);
}
}
I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.
so basically I only know how to read integers and store them in an array, but what about both Integers and words? Here is my code for doing just the integers from an array from an earlier time, the method is readFileAndReturnWords. How could I change it to read both integers and words as well?
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WordsNsuch {
public static void main(String [ ] commandlineArguments){
//Error message when arg is blank
if(commandlineArguments.length == 0) {
System.err.println("You did not enter anything");
System.exit(0);
}
String[] array = readFileAndReturnWords(commandlineArguments[0]);
sortAndPrintTheArray(array, commandlineArguments[0]);
}
//RIGHT HERE GUYS
public static String readFileAndReturnWords(String filename){
String[] temp = new String[10000];
int i = 0;
//connects file
File file = new File(filename);
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
//When arg is mistyped
catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
//counts the amount of strings
if (inputFile != null) {
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();//This is a problem
i++;
} catch (InputMismatchException Exception2) {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
String[] array = new String[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new String[] {};
}
public static void sortAndPrintTheArray(String [] array, String filename){
Sorting.display = false;
Sorting.insertionSort(array, 0, array.length-1);//figure out how to get the last word later
System.out.println("ASCII listing of words in file:\"" + filename + "\" = " + array.length);
for (int i = 0; i < array.length; i++) {
System.out.println("index = " + i + "," + " element = " + array[i]);
}
}
}
I'm not going into your code but here is an example of how to read both numbers and words :
//while there's anything including numbers and words
while(textfile.hasNext())
{
//if there's a number, read it!
if(textfile.hasNextInt())
{
int number = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
String word1 = textfile.hasNext();
String word2 = textfile.hastNext();
f(textfile.hasNextInt())
{
int number2 = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
.......
}
Anytime if there's a number, try if-else statement ("else" statement depends on how big and how full your textfile is with numbers and letters) but when after a number there follows a String use else statement similar to the else statement in the code that I've mentioned; when there's a String, just read that with textfileName.hasNext() w/o any conditionals. Any question, do not hesitate to ask!
Here is a little code snippet to help you out, I have based it on your code.
I would handle the arrays slightly differently but I just want to point you in the right direction, not do the work for you.
This will create two arrays: ints and strs one staininging the integers and one containing the strings.
int[] ints = new int[10000];
String[] strs = new String[10000];
int i = 0;
int j = 0;
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
} catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
ints[i++] = inputFile.nextInt();
} else {
strs[j++] = inputFile.next();
}
}
}
Hope this helps!
For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays. The code below is features the class that I have written. It is largely based on my CSV class, the FileInput class http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileInput.java) and FileOutput Class (http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileOutput.java).
When running the program to read a text file I get the following error message:
"Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at com.gc01.FileManager.FileInput.<init>(FileInput.java:22)
at com.gc01.FileManager.ByteManager.readByte(ByteManager.java:28)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:85)"
And my code:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rows = sc.nextByte();
return fileName;
}
public void readByte(final String fileName, int columns, int rows){
FileInput in = new FileInput(fileName);
int [] [] data = new int[rows] [columns];
String [] line;
for (int i = 0; i < rows; i++){
line = in.readString().split("\t");
for (int j = 0; j < columns; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
System.out.println("******File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columnsOut = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rowsOut = sc.nextByte();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT, int columnsOut, int rowsOut){
FileOutput createData = new FileOutput (fileNameOUT);
int newData = 0;
System.out.println("Enter data. To finish, enter 'TERMINATE_FILE'");
while(!"TERMINATE_FILE".equals(newData)){
Scanner input = new Scanner (System.in);
int [] [] data = new int[rowsOut] [columnsOut];
String [] line = null;
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newData = input.nextByte());
System.out.println("\t");
for (int j = 0; j < columnsOut; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
createData.close();
}
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.getByteFile();
object.readByte(null, 0, 0);
} else if ("2".equals(choice)){
object.chooseFileOutput();
object.writeByte(null, 0, 0);
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
UPDATE
Thank you for your comments and advice below, I have now run into a another problem that I can not work out. I have re-written my readByte method. However when I now run it, I no longer get compiler errors (thanks to your advice), however I can not get the contents of the file to print. Instead the console just displays "File Read". I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere. The contents of the file I am trying to read is also below.
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
File Contents (separated by tab)
123 6565
123 6564
123 6563
123 6562
This code is the source of the error
object.readByte(null, 0, 0);
The parameter null is invalid state for FileInput. It should be a file name string.
You are passing null argument to readByte() from main()
object.readByte(null, 0, 0);
And in readByte()
FileInput in = new FileInput(fileName); //here it throws NPE
Pass valid file name.
NullPointerException
public class NullPointerException
extends RuntimeException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.