Filling a 2d character array from a file in java - java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}

I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}

Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());

There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

Related

Problems with iterated nextLine function

I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);

null pointer exception string builder

I am trying to use the setCharAt method in a StringBuilder but I am getting a null pointer exception. Is there a way I can add values to the StringBuilder array I have made so I wont get these error.
From research I have found the .append() method but I'm not even sure how it works.
import java.util.*; // Allows for the input of a scanner method.
import java.io.*; // Allows for the inputting and outputting of a data file.
import java.lang.*; // Allows for the use of String Methods.
//////////////////////////////////////////////////////////////////////////////////////
public class TESTY
{
static Scanner testanswers;
static PrintWriter testresults;
public static void main(String[] args) throws IOException
{
testanswers = new Scanner(new FileReader("TestInput.dat"));
testresults = new PrintWriter("TestOutput.dat");
String StudentID;
String answers;
// Reads first two lines first to know how many records there are.
String answerKey = testanswers.nextLine();
int count = Integer.parseInt(testanswers.nextLine());
// Allocate the array for the size needed.
String[][] answerArray = new String[count][];
for (int i = 0; i < count; i++)
{
String line = testanswers.nextLine();
answerArray[i] = line.split(" ", 2);
}
for(int row = 0; row < answerArray.length; row++)
{
for(int col = 0; col < answerArray[row].length; col++)
{
System.out.print(answerArray[row][col] + " ");
}
System.out.println();
}
gradeData(answerArray, answerKey);
testanswers.close();
testresults.close();
}
///////////////////////////////////////////////////////////
//Method: gradeData
//Description: This method will grade testanswers showing
//what was missed, skipped, letter grade, and percentage.
///////////////////////////////////////////////////////////
public static double gradeData(String[][] answerArray, String answerKey)
{
String key = answerKey;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[5];
String studAnswers;
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++) /// Counting rows
{
studAnswers = answerArray[rowIndex][1].replace(" ", "S"); ///Counts rows, Col stay static index 1
for(int charIndex = 0; charIndex < studAnswers.length(); charIndex++)
{
if(studAnswers.charAt(charIndex) == key.charAt(charIndex))
{
Points += 2;
}
else if(studAnswers.charAt(charIndex) == 'S')
{
Points --;
}
else if(studAnswers.charAt(charIndex) != key.charAt(charIndex))
{
for(int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i].setCharAt(charIndex, 'X');
}
Points -= 2;
}
}
System.out.println(Points);
}
return Points;
}
}
The error is occurring on line 91 :
wrongAnswers[i].setCharAt(charIndex, 'X');
You have declared an array of StringBuilders, but you haven't initialized any of the slots, so they're still null.
Initialize them:
StringBuilder[] wrongAnswers = new StringBuilder[5];
for (int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i] = new StringBuilder();
}
Additionally, using setCharAt won't work here, because initially, there is nothing in the StringBuilder. Depending on what you want here, you may need to just call append, or you may initially want a string full of spaces so that you can set a specific character to 'X'.
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 empty StringBuilders but 5 null StringBuilders.
You need to call something like
wrongAnswers[i] = new StringBuilder()
in order to initialize your 5 array members.
Your problem is that
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 StringBuilder objects. It only creates an array with 5 null StringBuilder references. You need to create each StringBuilder separately with a line such as
wrongAnswers[i] = new StringBuilder();
inside a loop over i.

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

List<String> ----> to int [ ] [ ] arr

Well I have been stumped as to the best way to do this, I have written the code to read in lines of code from txt files as List. I can then print specific parts or convert this to an array of objects. But, ultimately I would like to have just a 2d int array you can see often in C/C++. I am very green when it comes to java, having only started earlier this week. I have like it up until this point of making dynamic 2d arrays at run time. Can any of you suggest a good way to get to a 2d int array from where i am currently stuck. I was just about to convert it to a char array using 'toChar', then to take the (value#index-48) and store it in its corresponding spot, but that seems pretty ghetto to me.
====updated==========================
eh, thanks for all the replies, but I just figured out how to do it using doubles, so for anyone else, here you go. I would still rather have int, since I have already built my other matrixops classes using this type, but Double shouldn't be an issue i guess.
package uaa.cse215;
import java.io.*;
import java.util.*;
public class ReadMatrix {
private Double[][] A;
private Double[][] B;
private int count;
public int filedir(String matrix) throws Exception{
Double[][] Temp;
String[] arr;
BufferedReader rd = new BufferedReader(new FileReader(matrix));
String s;
List<String> textFile = new ArrayList<String>();
while ((s=rd.readLine())!=null) {
textFile.add(s);
}
String splitarray[] = textFile.get(0).split(" ");//run once to grab # cols
int rows = textFile.size();//number of rows
int cols = splitarray.length;//number of cols
Temp = new Double[rows][cols]; // now can initiate array
for (int i=0; i<rows; i++) {
s = textFile.get(i);
arr = s.split(" ");
for (int j=0; j<cols; j++) {
Temp[i][j] = Double.parseDouble(arr[j]);
}
}
count++;
if (count == 1){
A = Temp;
}
else
B = Temp;
rd.close();
return(1);
}
}
Please note that Java has the char data type which is a 16bit unsigned integer holding a UTF-16 code point. int is in Java always a signed 32 bit integer. So if you want a C like Arrays of chars representing the content of a String, you should use a char[][]
To convert the content of your List<String> into a 2d array you can use the following code:
char[][] twoDarray = new char[textFile.size()];
for(int i = 0; i < textFile.size(); i+)
{
twoDarray[i] = textFile.get(i).toCharArray();
}
The array twoDarray then contains all Strings each as a char array.
This line won't compile
splitarray[j] = textFile.get(i).split(" ");
as splitarray[j] is of type String and split returns an array of Strings
Do the following instead:
for(int row=0;row<textFile.size();row++){
String[] splitarray = textFile.get(row).split(" ");
for(int col=0;col<splitarray.length;col++){
tmp[row][col] = Integer.parse(splitarray[col]);
}
}
if the input matrix dimentions are dynamic or jagged you can use
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
to read numbers and than copy it to raw 2d array if you want.
java.util.Scanner has many handy methods for reading "typed" data from input
Here's an example reading file to 2D array
public static int[][] read2DArray(String fileName) throws FileNotFoundException {
Scanner sc = null;
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int columnCount = 0;
int[][] arr = null;
try {
sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
// Read line
String line = sc.nextLine();
// Split it
String[] nums = line.split(" ");
if (nums.length > columnCount) {
columnCount = nums.length;
}
// Convert to integers and add to list
list.add(new ArrayList<Integer>());
for (String n : nums) {
list.get(list.size() - 1).add(new Integer(n));
}
}
// Convert list to array
int rowCount = list.size();
arr = new int[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < list.get(i).size(); j++) {
arr[i][j] = list.get(i).get(j);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return arr;
}
Assuming your data file contains ascii-represented numbers that you want parsed into integers:
11 -9 13
12 55 102
1 1 1024
Then you can use the Integer(String s) constructor to parse your string objects.
Also, I suggest splitting each row only once. It won't matter much for small arrays, but the larger your inputs get, the more you'll needlessly recompute the splits.
An (untested) re-writing:
int tmp[][] = new int [rows][cols];
for(int i=0;i<rows;i++){
splitarray = textFile.get(i).split(" ");
for(int j=0;j<cols;j++){
tmp[i][j] = Integer(splitarray[j]);
}
}

Reading 2-D array from a file

I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :
import java.util.*;
import java.lang.*;
import java.io.*;
public class appMainNineSix {
/**
* #param args
*/
public static void main(String[] args)
throws java.io.FileNotFoundException{
// TODO Auto-generated method stub
Scanner input = new Scanner (new File("src/array.txt"));
int m = 3;
int n = 5;
int[][] a = new int [m][n];
while (input.next()!=null){
for (int i=0;i<m;i++){
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
}
}
//print the input matrix
System.out.println("The input sorted matrix is : ");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.println(a[i][j]);
}
}
}
while (input.next()!=null)
This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())
Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.
Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt())
{
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i &lt rows; ++i)
{
for(int j = 0; j &lt columns; ++j)
{
if(input.hasNextInt())
{
a[i][j] = input.nextInt();
}
}
}
An alternative using ArrayLists (no pre-reading required):
// read in the data
ArrayList&ltArrayList&ltInteger&gt&gt a = new ArrayList&ltArrayList&ltInteger&gt&gt();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
Scanner colReader = new Scanner(input.nextLine());
ArrayList col = new ArrayList();
while(colReader.hasNextInt())
{
col.add(colReader.nextInt());
}
a.add(col);
}
The problem is when u reach the end of the file it throughs an exception that no usch element exist.
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner input = new Scanner(new File("array.txt"));
int m = 3;
int n = 5;
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{// System.out.println("number is ");
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
System.out.println("The input sorted matrix is : ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println(a[i][j]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I knew that making catch without processing the exception but it temporary works.
Please be aware I put the file outside the source folder.
Well the problem may be that you've got that pair of nested loops to read the numbers stuck inside that while loop. Why would you want to re-read the array values after you've read them once? And note that if there's anything in the file after the last number, then you'll fill the array in with whatever .nextInt() returns after end-of-file has been reached!
edit — well .nextInt() should throw an exception I guess when input runs out, so that may not be the problem.
Start simple...
change:
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
to:
for (int j=0;j<n;j++)
{
int value;
value = input.nextInt();
a[i][j] = value;
System.out.println("value[" + i + "][" + j + " = " + value);
}
And make sure that the values are read in.
Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).
You can try Using Guava ,
public class MatrixFile {
private final int[][] matrix;
public MatrixFile(String filepath) {
// since we don't know how many rows there is going to be, we will
// create a list to hold dynamic arrays instead
List<int[]> dynamicMatrix = Lists.newArrayList();
try {
// use Guava to read file from resources folder
String content = Resources.toString(
Resources.getResource(filepath),
Charsets.UTF_8
);
Arrays.stream(content.split("\n"))
.forEach(line -> {
dynamicMatrix.add(
Arrays.stream(line.split(" "))
.mapToInt(Integer::parseInt)
.toArray()
);
});
} catch (IOException e) {
// in case of error, always log error!
System.err.println("MatrixFile has trouble reading file");
e.printStackTrace();
}
matrix = dynamicMatrix.stream().toArray(int[][]::new);
}

Categories

Resources