reading 2d array from txt file java scanner - java

I keep getting:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Driver0.readFile(Driver0.java:38)
at Driver0.main(Driver0.java:18)
Trying to use the scanner class since it's all I know so far. any help appreciated. Trying to read the 2d array but it never reads it fully. My input.txt file is:
3 5
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
import java.io.*;
import java.util.*;
public class Driver0 {
//public static String fileName; // declare so it may be used outside of main
public static int[][] array; // declare as empty until given dimensions
public static int dimensionA, dimensionB; // dimensions used in methods
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the name of the data file?");
System.out.print("> ");
String fileName = input.nextLine();
readFile(fileName);
String nextCommand = "";
while (!(nextCommand.equals("quit"))) {
System.out.println("\nNext command");
System.out.print("> ");
nextCommand = input.nextLine();
choice (nextCommand);
}
}
public static void choice(String command) {
switch (command) {
case "help": System.out.println("show array\nrows sorted\ncols sorted"+
"increase row i by n\nincrease col j by n\nquit\n");
break;
default: showArray();
}
}
public static void readFile(String fileName) {
try {
Scanner foo = new Scanner(fileName);
dimensionA = foo.nextInt();
dimensionB = foo.nextInt();
array = new int[dimensionA][dimensionB];
while (foo.hasNext()) {
for (int row = 0; row < dimensionA; row++) {
foo.nextLine();
for (int column = 0; column < dimensionB; column++) {
array[row][column] = foo.nextInt();
}
}
}
foo.close();
}
catch(Exception e) {
e.printStackTrace(); // displays type of error
}
}
public static void showArray() {
for (int ro = 0; ro < dimensionA; ro++) {
for (int col = 0; col < dimensionB; col++) {
System.out.print(array[ro][col]);
}
System.out.println();
}
}
}

Go through methods in the Scanner class.
Specially, the hasXXX() and nextXXX() methods, they come in pairs. Try not to mix-match those methods which will make things complicated. You are using nextInt(), hasNext(), and nextLine(). The docs also explains what these methods do when you invoke them.
For your case, the methods hasNextLine() and nextLine() will be enough if you are willing to use the String.split(). You can split the string returned by nextLine() and parse the integer and assign it to the array element.

I think it's better to use ArrayList. try this
package readfile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Read {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
List<String[]> list = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new FileReader("/home/user/My_Folder/read_me.txt"));
while ((line = reader.readLine())!=null) {
list.add(getArray(line));
}
reader.close();
for (String[] stringArr : list) {
for(String str : stringArr){
System.out.print(str+" ");
}
System.out.println("");
}
}
private static String[] getArray(String s){
String[] array = s.split("\\s");
return array;
}
}

Related

search for multiple strings from a text file in java

I'm trying to search of multiple words given from a user ( i used array to store them in ) from one txt file , and then if that word presented once in the file it will be displayed and if it's not it won't.
also for the words itself , if it's duplicated it will search it once.
the problem now when i search for only one it worked , but with multiple words it keeps repeated that the word isn't present even if it's there.
i would like to know where should i put the for loop and what's the possible changes.
package search;
import java.io.*;
import java.util.Scanner;
public class Read {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String[] words=null;
FileReader fr = new FileReader("java.txt");
BufferedReader br = new BufferedReader(fr);
String s;
System.out.println("Enter the number of words:");
Integer n = sc.nextInt();
String wordsArray[] = new String[n];
System.out.println("Enter words:");
for(int i=0; i<n; i++)
{
wordsArray[i]=sc.next();
}
for (int i = 0; i <n; i++) {
int count=0; //Intialize the word to zero
while((s=br.readLine())!=null) //Reading Content from the file
{
{
words=s.split(" "); //Split the word using space
for (String word : words)
{
if (word.equals(wordsArray[i])) //Search for the given word
{
count++; //If Present increase the count by one
}
}
if(count == 1)
{
System.out.println(wordsArray[i] + " is unique in file ");
}
else if (count == 0)
{
System.out.println("The given word is not present in the file");
}
else
{
System.out.println("The given word is present in the file more than 1 time");
}
}
}
}
fr.close();
}
}
The code which you wrote is error prone and remember always there should be proper break condition when you use while loop.
Try the following code:
public class Read {
public static void main(String[] args)
{
// Declaring the String
String paragraph = "These words can be searched";
// Declaring a HashMap of <String, Integer>
Map<String, Integer> hashMap = new HashMap<>();
// Splitting the words of string
// and storing them in the array.
String[] words = new String[]{"These", "can", "searched"};
for (String word : words) {
// Asking whether the HashMap contains the
// key or not. Will return null if not.
Integer integer = hashMap.get(word);
if (integer == null)
// Storing the word as key and its
// occurrence as value in the HashMap.
hashMap.put(word, 1);
else {
// Incrementing the value if the word
// is already present in the HashMap.
hashMap.put(word, integer + 1);
}
}
System.out.println(hashMap);
}
}
I've tried by hard coding the values, you can take words and paragraph from the file and console.
The 'proper' class to use for extracting words from text is java.text.BreakIterator
You can try the following (reading line-wise in case of large files)
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WordFinder {
public static void main(String[] args) {
try {
if (args.length < 2) {
WordFinder.usage();
System.exit(1);
}
ArrayList<String> argv = new ArrayList<>(Arrays.asList(args));
String path = argv.remove(0);
List<String> found = WordFinder.findWords(Files.lines(Paths.get(path)), argv);
System.out.printf("Found the following word(s) in file at %s%n", path);
System.out.println(found);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static List<String> findWords(Stream<String> lines, ArrayList<String> searchWords) {
List<String> result = new ArrayList<>();
BreakIterator boundary = BreakIterator.getWordInstance();
lines.forEach(line -> {
boundary.setText(line);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String candidate = line.substring(start, end);
if (searchWords.contains(candidate)) {
result.add(candidate);
searchWords.remove(candidate);
}
}
});
return result;
}
private static void usage() {
System.err.println("Usage: java WordFinder <Path to input file> <Word 1> [<Word 2> <Word 3>...]");
}
}
Sample run:
goose#t410:/tmp$ echo 'the quick brown fox jumps over the lazy dog' >quick.txt
goose#t410:/tmp$ java WordFinder quick.txt dog goose the did quick over
Found the following word(s) in file at quick.txt
[the, quick, over, dog]
goose#t410:/tmp$

Is there a way to have a text file be broken into characters and pass this into an arrayList which then is fed as a parameter to a method?

I have the following pieces of code and I am attempting to create an ArrayList 'list', which takes in 'ch' from the text file for each element i. The ArrayList then is fed as a parameter to the method of 'HelloPrinter' class.
I am getting no errors, but the 'reverse.txt' file isn't reversing the lettering as it is suppose to with the 'recursiveReverse' method.
Test/Driver:
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.lang.Class;
public class HelloPrinterDriver
{
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<Character> list = new ArrayList<>();
int i = 1;
File inputFile = new File("src/reverse.txt");
Scanner in = new Scanner(inputFile);
in.useDelimiter("");
//System.out.println(list.getClass().getSimpleName());
//PrintWriter out = new PrintWriter("src/reverse.txt");
while(in.hasNext())
{
char ch = in.next().charAt(0);
list.add(ch);
i++;
}
HelloPrinter.recursiveReverse(list);
in.close();
//out.close();
}
}
Class:
import java.util.*;
public class HelloPrinter
{
public static String recursiveReverse(ArrayList<Character> str)
{
Stack<Character> st = new Stack<>();
for(int i=0; i<str.size(); i++)
st.push(str.get(i));
for (int i=0; i<str.size(); i++) {
str.set(i,st.peek());
st.pop();
}
return String.valueOf(str);// converting character array to string
}
}
This should provide the result you are seeking:
#Test
public void test2() throws FileNotFoundException {
final ArrayList<Character> list = new ArrayList<>();
final File inputFile = new File("src/test/resources/reverse.txt");
// Scanner implements AutoCloseable so we can wrap it in a try and it will be closed automatically for us.
try (final Scanner in = new Scanner(inputFile)) {
in.useDelimiter("");
while (in.hasNext()) {
final char ch = in.next().charAt(0);
list.add(ch);
}
}
// Now reverse the order of the characters in the list.
Collections.reverse(list);
System.out.println(String.valueOf(list));
}

Is there a way for my spellchecker to properly work

The problem is my spellchecker, that I am trying to make. I have a dictionary file that contains large amount of words to compare with the user input so it can detect any possible spelling errors. The problem with mine, is that regardless of what you type it will always say that the spelling is incorrect when it is not. Is there any solution or a better method to detect selling errors of the user input.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
final String theDictionary = "dictionary.txt";
String[] words = dictionary(theDictionary);
boolean correctSpelling = checking(words, userWord);
if (!correctSpelling)
{
System.out.println("Incorrect spelling");
}
else
{
System.out.println("The spelling is correct");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException
{
final String fileName = "dictionary.txt";
Scanner dictionary = new Scanner(new File(fileName));
int dictionaryLength =0;
while (dictionary.hasNext())
{
++dictionaryLength;
dictionary.nextLine();
}
String [] theWords = new String[dictionaryLength];
for ( int x = 0; x < theWords.length ; x++)
dictionary.close();
return theWords;
}
public static boolean checking(String[] dictionary, String userWord)
{
boolean correctSpelling = false;
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
correctSpelling = true;
}
else
correctSpelling = false;
}
return correctSpelling;
}
}
The result I get is:
Please enter a String
hello
Incorrect spelling
As you can see the, even though my spelling was correct, it gives an error that the spelling was incorrect. Any help would be great and thank you in advance.
Yes. Return from checking on true. As you have it now, it can only be true if the last word matches. Like,
public static boolean checking(String[] dictionary, String userWord) {
for ( int i =0; i < dictionary.length; i++) {
if (userWord.equals(dictionary[i])) {
return true;
}
}
return false;
}
Also, you need to populate your dictionary by adding words to your array.
And, I would prefer try-with-resources over explicit close() calls. Something like,
public static String[] dictionary(String filename) throws FileNotFoundException {
final String fileName = "dictionary.txt";
int dictionaryLength = 0, i = 0;
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
++dictionaryLength;
dictionary.nextLine();
}
}
String[] theWords = new String[dictionaryLength];
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords[i] = dictionary.nextLine();
i++;
}
}
return theWords;
}

Parsing a CSV into 2D array generates NullPointerException

Using ReadInputCSVFromFile method to read the sample CSV from file and parse it to a String array after using split(",") function and pass it to a 2D array to read it fully.
PrintResultsForTesting method would be only for printing out the 2D array for visual overlook.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class CSVReader {
public static String[][] readIntoArray;
public static String[][] myArray;
public static String[][] csvResults;
public static int countRow = 0;
public static int countColumn = 0;
public static void main(String[] args) {
csvResults = ReadInputCSVFromFile(myArray);
PrintResultsForTesting(csvResults);
}
public static void PrintResultsForTesting(String[][] csvResults) {
String[][] newMyArray = new String[myArray.length][myArray[0].length];
for (int i = 0; i < csvResults.length; ++i) {
for (int j = 0; j < csvResults[0].length; ++j) {
System.out.println(csvResults[i][j]);
}
}
}
public static String[][] ReadInputCSVFromFile(String[][] myArray) {
countRow = 0;
countColumn = 0;
Scanner scanner;
String inputLine;
String fileLocation;
fileLocation = "D://WorkSpace_Git//methods//iq-distribution//docs/SAP.csv";
try {
scanner = new Scanner(new BufferedReader(new FileReader(fileLocation)));
while (scanner.hasNext()) {
inputLine = scanner.nextLine();
String[] readIntoArray = inputLine.split(",");
// count rows and columns
++countRow;
countColumn = readIntoArray.length;
myArray = new String[countRow][countColumn];
}
for (int i = 0; i < countRow; ++i) {
for (int j = 0; j < countColumn; ++j) {
myArray[i][j] = readIntoArray[i][j];
}
}
System.out.println("Rows: " + countRow + '\n' + "Columns: " + countColumn);
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return myArray;
}
}
The error is:
Exception in thread "main" java.lang.NullPointerException at project.CSVReader.ReadInputCSVFromFile(CSVReader.java:52) at project.CSVReader.main(CSVReader.java:16) Process finished with exit code 1
After looking briefly at your code, I could spot a bug. When this method is called:
public static String[][] ReadInputCSVFromFile(String[][] myArray) {
myArray is null.
If you want to write to the array, you will need to instantiate the array first.
If you are using arrays actually you should know in advance its dimensions. If you do not know it, consider using some implementation of java.util.List - like java.util.ArrayList.
Another problem is exception handling. If the file is not found, then the exception is caught and you still call this method PrintResultsForTesting with unpredicatable results. Better to use a throws clause and stop the execution alltogether. So instead of the try catch in method ReadInputCSVFromFile just use a throws FileNotFoundException in this method.

Counting the amount of times each letter shows in a file

Essentially, this code takes a file (which is a few paragraphs of text) and counts the amount of times each letter appears and prints it onto the console. While I've finished all the code in terms of calculation, I'm running into an exception. When I run this, it shows:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at LetterCount.countOccurrences(LetterCount.java:29)
at LetterCount.main(LetterCount.java:20)
Here is my code:
// Document your class here
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
public class LetterCount {
public final static String FILENAME = "testFile.txt";
// Driver to test LetterInventory class
public static void main(String[] args) {
Scanner inputFile = null;
try {
inputFile = new Scanner(new File(FILENAME));
} catch (Exception e) {
System.out.println("File could not be opened: " + FILENAME);
System.exit(0);
}
int[] counts = countOccurrences(inputFile);
displayTable(counts);
resetTable(counts);
}
public static int[] countOccurrences (Scanner inputFile) {
int[]counts = new int[26];
char[] characters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
while (inputFile.hasNextLine()) {
String theWord = inputFile.next();
theWord = theWord.toLowerCase();
for (int j = 0; j < theWord.length(); j++) {
for (int counter = 0; counter < 26; counter++) {
if (theWord.charAt(j) == characters[counter]) {
counts[counter] += 1;
}
}
}
}
return counts;
}
public static void displayTable (int[] counts) {
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t" + counts[index]);
}
}
public static void resetTable (int[] counts) {
System.out.println();
for (int index = 0; index < 26; index++) {
System.out.println((char)('a' + index) + ":\t0");
}
}
}
When I clicked on the highlighted parts of NoSuchElementException, I saw that it was referring to the String I created. What am I doing wrong, and what can I do to fix it?
The method you use to read the data should be of the same type as the one you use to check if there is more data.
In your while statement, you use inputFile.hasNextLine(), so on the line after it, you should use inputFile.nextLine() (rather than inputFile.next() as you do now).
Alternatively, you can change the while statement to use inputFile.hasNext().
No guarantees, but try using inputFile.hasNext() in your while instead of inputFile.hasNextLine(). A next line being available is not necessarily the same thing as a next word being available.
You don't need the characters array (you can use the same math you have in display to perform the addition of counts). Also, you should be consistent with how you call Scanner.hasNextLine() and Scanner.next() (check for next with hasNext()). Something like,
public static int[] countOccurrences(Scanner inputFile) {
int[] counts = new int[26];
while (inputFile.hasNext()) {
String theWord = inputFile.next().toLowerCase();
for (char ch : theWord.toCharArray()) {
if (Character.isLetter(ch)) {
counts[ch - 'a']++;
}
}
}
return counts;
}

Categories