Hi for my HW I am suppose to read a text file of '.' and 'x' representing cells in Conway's Game of Life. I'm having trouble with reading the given text input and adding it into my double integer arrays. Specifically the rowcounter and columncounter part I'm sure there is a better way to do it but when I tried for loops it only read one row. I included previous parts of the code just in case. Thanks.
// Initiate file
File inputfile = new File(inputfilename);
try {
input = new Scanner(inputfile);
} catch (Exception ie) {
}
// Get array size
int[] arraysize = new int[2];
while (input.hasNextInt()) {
for (int i = 0; i < 2; i++) {
int token = input.nextInt();
arraysize[i] = token;
}
}
//System.out.println(Arrays.toString(arraysize));
// Create Array
int[][] newarray = new int[arraysize[0]][arraysize[1]];
//System.out.println(Arrays.deepToString(newarray));
// Read initial
int rowcounter = 0;
int columncounter = 0;
while (input.hasNextLine()) {
Scanner inputtoken = new Scanner(input.nextLine());
while (inputtoken.hasNext()) {
String token = inputtoken.next();
//System.out.print(token);
char xchar = token.charAt(0);
if (xchar == 'x') {
newarray[rowcounter][columncounter] = 1;
} else {
newarray[rowcounter][columncounter] = 0;
//System.out.print(rowcounter);
}
columncounter = columncounter + 1;
//System.out.print(columncounter);
}
columncounter = 0;
System.out.println();
rowcounter = rowcounter + 1;
//System.out.print(rowcounter);
}
System.out.println(Arrays.deepToString(newarray));
Related
All the examples that i have seen involve specifying the number of rows and columns at the start of the file but the method I'm working on reads a file with the following:
1.0 2.0
3.0 4.0
and using this data creates a 2d array and stores it without specifying the number of rows and columns.
Here's the code I have written:
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
int rows =0;
int columns =0;
while(input.hasNextLine()){
String line = input.nextLine();
rows++;
columns = line.length();
}
double[][] d = new double[rows][columns]
return d;
}
I'm unsure of how to add these values now that I have created the 2d array. i tried this but got an InputMismatchException.
Scanner s1 = new Scanner(file);
double[][] d = new double[rows][columns]
for (int i= 0;i<rows;i++) {
for (int j= 0;i<rows;j++) {
d[i][j] = s1.nextDouble();
}
}
if you just want to use the basic arrays you can achieve it with something like
Scanner input = new Scanner(new FileReader(file));
int row=0;
int col =0;
String s="";
//count number of rows
while(input.hasNextLine()) {
row++;
s=input.nextLine();
}
//count number of columns
for(char c: s.toCharArray()) {
if(c==' ')
col++;
}
col++; // since columns is one greater than the number of spaces
//close the file
input.close();
// and open it again to start reading it from the begining
input = new Scanner(new FileReader(file));
//declare a new array
double[][] d = new double[row][col];
int rowNum=0;
while(input.hasNextLine()) {
for(int i=0; i< col; i++) {
d[rowNum][i]= input.nextDouble();
}
rowNum++;
}
However if you prefer to use java collection you can avoid reading the file again. Just store the strings in a list and iterate over the list to extract elements from it.
Based on your input, Your columns = line.length(); is returning 7 rather than 2 as it returns the String length.
Hence try calculating the no of columns in the row columns = line.split(" ").length;
Also while trying to read your input you were using index i for the 2nd for-loop. It should be like below,
for (int i= 0;i<rows;i++) {
for (int j= 0;j<columns;j++) {
d[i][j] = s1.nextDouble();
}
}
In order to work with arrays of unknown size you should read the data into a Collection (such as a List). However, Collection(s) only work with the wrapper-types; so you will need to copy the elements back into an array of double(s) if that is what you really need. Something like,
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
List<List<Double>> al = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<Double> ll = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
ll.add(sc.nextDouble());
}
al.add(ll);
}
double[][] d = new double[al.size()][];
for (int i = 0; i < al.size(); i++) {
List<Double> list = al.get(i);
d[i] = new double[list.size()];
for (int j = 0; j < d[i].length; j++) {
d[i][j] = list.get(j);
}
}
return d;
}
Which I tested by creating a file in my home folder with your contents and running it like so
public static void main(String[] args) {
String file = System.getProperty("user.home") + File.separator + "temp.txt";
try {
System.out.println(Arrays.deepToString(readMatrixFrom(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
And I get (as I assume you wanted)
[[1.0, 2.0], [3.0, 4.0]]
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code
So I'm trying to read in a string from a file. However, I want each string to contain exactly 64 characters or less if the last string doesn't have 64 in it. So essentially I have a counter, when that counter reaches 64, I set the array of characters to a string, go to the next row and reset the count to zero. However I'm not getting output of any kind when I run it. Any help is appreciated. Here is a snippet of my code
public static void main(String[] args) throws IOException{
File input = null;
if (1 < args.length) {
input = new File(args[1]);
}
else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(0);
}
String key = args[0];
BufferedReader reader = null;
int len;
Scanner scan = new Scanner(System.in);
System.out.println("How many lines in the file?");
if(scan.hasNextInt()){
len = scan.nextInt();
}
else{
System.out.println("Please enter an integer: ");
scan.next();
len = scan.nextInt();
}
scan.close();
String[] inputText = new String[2 * len];
String[] encryptText = new String[2 * len];
char[][] inputCharArr = new char[2 * len][64];
reader = new BufferedReader(new FileReader(input));
int r;
int counter = 0;
int row = 0;
while ((r = reader.read()) != -1) {
char ch = (char) r;
if(counter == 64){
String temp = new String(inputCharArr[row]);
inputText[row] = temp;
encryptText[row] = inputText[row];
System.out.println(inputText[row]);
row++;
counter = 0;
}
if(row == len){
break;
}
inputCharArr[row][counter] = ch;
counter++;
}
Edit: Is this close?
CharBuffer cbuf = CharBuffer.allocate(64);
int counter = 0;
while (reader.read(cbuf) != -1) {
inputText[counter] = cbuf.toString();
encryptText[counter] = inputText[counter];
counter++;
cbuf.clear();
}
I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.
What I need to do is to implement the 0-1 Knapsack problem. There is an input file named "In0302.txt" and an output file named "Out0302.txt". The program gets values from INPUT file and saves the results to OUTPUT file. I got my input values on paper from my "dr".
Putting them to the file seems to be ok in OUTPUT file. But... on classes "dr" tried to put other values in INPUT file, but the program didn't work. What is more there was no even an error, but the program was still compiling and compiling... and I can't get know where the problem is. Does anybody would try to change something in this code or tell me what is wrong ?
INPUT:
4 6
2 1
3 2
3 4
4 5
OUTPUT:
1 4
2 3
JAVA CODE:
public class Knapsack {
public static int max(int a, int b){
if (a > b){
return a;
}
else{
return b;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args){
int n = 0, W = 0, p[] = null, w[] = null, S[][] = null, S_object[][] = null;
//s[][] = arrays with values
try {
FileReader fr = new FileReader("In0302.txt");
BufferedReader in = new BufferedReader(fr);
String line = in.readLine();
String[] cols = line.split(" ");
n = Integer.parseInt(cols[0]); W = Integer.parseInt(cols[1]);
p = new int[n+1]; w = new int[n+1];
int k = 1;
while ((line = in.readLine()) != null) {
cols = line.split(" ");
p[k] = Integer.parseInt(cols[0]);
w[k] = Integer.parseInt(cols[1]);
k++;
}
S = new int[W+1][n+1];
S_object = new int[W+1][n+1];
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
if (i == 0){
S[weight][i] = 0;
S_object[weight][i] = 0;
}
else if (weight < w[i]){
S[weight][i] = S[weight][i-1];
S_object[weight][i] = S_object[weight][i-1];
}
else if (weight >= w[i-1]){
S[weight][i]=max(S[weight][i-1],S[weight-w[i]][i-1]+p[i]);
if ((max(S[weight][i-1], S[weight-w[i]][i-1] + p[i]) == (S[weight-w[i]][i-1] + p[i]))) {
S_object[weight][i]=i;
} //added new element to bag
else {
S_object[weight][i]=S_object[weight][i-1];
} //nothing has been added
}
}
}
in.close();
fr.close();
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
File outputFile;
FileWriter out;
try{
outputFile = new File("Out0302.txt");
out = new FileWriter(outputFile);
String line = "";
int max_value = S[W][n];
for (int m = n; m > 0; m--){
if (S[W][m] == max_value){
line = " " + S_object[W][m] + "";
int temp = W;
while ((temp-w[S_object[temp][m]]) > 0){
temp = temp - w[S_object[temp][m]];
line += " " + S_object[temp][m];
}
out.write(line + "\n");
out.write("\n\t");
}
}
out.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
System.out.println("Arrar of values:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S[weight][i] + " ");
}
System.out.println("");
}
System.out.println("Array of objects:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S_object[weight][i] + " ");
}
System.out.println("");
}
}
}