Reading a text file into a char[][] array in Java - java

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
for(int row = 0; row < testAnswers.length; row++)
{
for(int col = 0; col < testAnswers[row].length; col++)
{
testAnswers[row][col] = input.next().toCharArray();
}
}
input.close();

The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
for(int row = 0; row < testAnswers.length; row++) {
for(int col = 0; col < testAnswers[row].length; col++) {
String token = r.next();
if (token.length() != 1)
throw new IllegalArgumentException("Answers must be one character");
testAnswers[row][col] = token.charAt(0);
}
}
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}

String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
//char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
int counter = 0;
while(scanner.hasNext())
{
copyString(testAnswers[counter], scanner.nextLine());
}
input.close();
its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
int size = x.length();
for (int i=0; i<size; i++){
arr[i] = x.CharAt(i);
}

Related

Filling a matrix with content from file

I'm getting an error on my code. The goal is to add the contents of a file to a matrix.Then ill eventually need to parse it to add it to a graph so that i can eventually perform a depth-first search on it. But until then i need to figure this error out. I can't figure out what exactly is causing the error. so any help would be nice.
Here is the error im getting:
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at DelivA.<init>(DelivA.java:53)
at Prog340.actionPerformed(Prog340.java:120
Here is the class i wrote.
public DelivA(File in, Graph gr) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
String outputFileName = baseFileName.concat("_out.txt");
outputFile = new File(outputFileName);
if (outputFile.exists()) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
} catch (Exception x) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
// --------------------------------Deliverable
// A-------------------------------------------//
FileReader f1 = null;
int c = 0;
int r = 0;
try {
f1 = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(f1);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String splitLine[] = line.split(" ");
c = splitLine.length;
r++;
}
String[][] matrix = new String[c][r];
#SuppressWarnings("resource")
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
String words = s1.next(); // will scan each row of the file
for (int col = 0; col < matrix[row].length; col++) {
char ch = words.charAt(col); // will put each character into array
matrix[row][col] = String.valueOf(ch);
}
}
}
}
Your problem is probably here:
String words = s1.next():
You are not verifying if there is any line available.
You should do something like this:
...
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
if (scanner.hasNextLine()){
String words = s1.next(); // will scan each row of the file
...
Of course you should rethink the code logic accordingly...

How to get data from a CSV file and place it in a list

I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)

Reading in file into a string array

How do I read in a file into a string array using Scanner? The file has a specified number of lines, lets say 100. There are plenty of examples in here using arrayList and BufferedReader but not Scanner or arrays that are already fixed in size.
public String[] array;
Scanner inputStream = null;
public String line;
public practice(String theFile) {
array = new String[100];
try {
inputStream = new Scanner(new FileInputStream(theFile));
while (inputStream.hasNextLine()) {
for (int i = 0; i < array.length; i++){
//dont know what to put here
}
}
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
inputStream.close();
}
You don't need to check for has next line because you have a fixed length and a try catch to handle it all. Just use the for loop but not the while loop. From there, it's just all scanner stuff:
for (int i = 0; i < array.length; i++)
{
array[i] = inputStream.nextLine();
}
int i = 0;
while (inputStream.hasNextLine() && i < array.length())
{
array[i] = inputStream.nextLine();
i++;
}

Encrypt/Decrypt file. ASCII +1 for encryption/decryption

I'm trying to read in a file of text, and "encrypt"/convert each letter to +1 from the ASCII table (I also want to "decrypt" so -1 for that). So "a" will become "b", "b" to "c" and so forth. I only need to convert alphabetic letters (Ignore everything else, print them as is). I'm having troubles with this part of the code:
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
I've figured out how to +1 the char, but I'm not sure how to add that back in to an array or print it out correctly (Since "morewords.add(ch)" is only going to add the char, instead of converting all the chars an adding a string). The "words.get(i).length()" takes the entire length of the array "words", when I just want the length of the string # position "i" in the array, so it throws an error since the length of the array is longer than the string word. I've been stuck on this for hours and I cannot figure it out. I'm thinking maybe I shouldn't read them in as strings and should have read them in as chars and this might have all been simpler?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> morewords = new ArrayList<Character>();
String fileName = ""; //Replace Test with this
File f;
Scanner fileIn;
System.out.println("Please enter a file name for encryption: ");
//fileName = in.nextLine();
fileName = "Test.txt";
try
{
//Build the file and attach a scanner to it
f = new File (fileName);
fileIn = new Scanner (f);
System.out.println(f.exists()); //For errors
int counting = 0;
//Reads in indvidual strings.
for(counting =0; fileIn.hasNext(); counting++)
{
words.add(fileIn.next());
System.out.println(words);
}
PrintWriter fileOut = new PrintWriter ("Backwards.txt");
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
fileOut.close();
}
catch(FileNotFoundException e)
{
System.out.println("Couldn't find file");
}
}
First in a for loops is right to do
for (int i = 0; i <= words.size()-1; i++){}
if you'r starting at 0 you end at length-1
what i have changed is
PrintWriter fileOut = new PrintWriter("C:/Backwards.txt");
for (int i = 0; i <= words.size()-1; i++)
{
for (int j = 0; j <= words.get(i).length()-1; j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch ++; // +=1
morewords.add(ch);
fileOut.print(ch);
}
fileOut.print(" ");
}
fileOut.close();
and it output right if i have understood right =)
this is my code
public static void main(String[] args) throws Exception
{
BufferedReader inChannel = new BufferedReader(new FileReader("C:/script.txt"));
BufferedWriter outChannel = new BufferedWriter(new FileWriter("C:/output.txt"));
String toParse = "";
while ( (toParse = inChannel.readLine()) != null )
{
String toWrite = "";
for(int i=0; i!=toParse.length();i++)
{
char c = toParse.charAt(i);
if(true) //check if must be encoded or not
{
c++;
toWrite += c;
}
}
outChannel.write(toWrite);
outChannel.newLine();
}
inChannel.close();
outChannel.close();
}
hope helped

Java Reading 2D array in from file, numbers separated by comma

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Categories