I am trying to read a txt file which consists of # and spaces to a 2D boolean array, so that technically a # represents true and a space represents false.
With the help of similar posts i got together a code, although they were reading integers to an array.
My code is:
public static void main(String[] args) {
String x;
String y;
Scanner fileName = null;
try {
fileName = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
x = fileName.nextLine();
y = fileName.nextLine();
boolean[][] cells = new boolean[x][y];
String finalX = fileName.nextLine();
String finalY = fileName.nextLine();
cells[finalX][finalY] = true;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j])
System.out.print("#");
else
System.out.print(" ");
}
System.out.println();
}
}
In my code where I have written boolean[][] cells = new boolean[x][y];
It says the [x] and [y] requires an int, but found a string. The same issue is for cells[finalX][finalY] = true;
I tried parsing i.e. Integer.parseInt(x) however this gets me an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "#####################"
At what point is my issue? If I parse to an Int, then it can't read the # correct?
I think this would solve it:
1- read each line of file until the end of it to get the number of cells rows which is n then take length of any String line to get number of columns which is m.
2- create boolean array cells[n][m].
3- read file line by line and put each line in String variable and iterate over the string variable characters if character is # put true in cells array otherwise put false.
String line="";
int n=0;
while(fileName.hasNextLine()){
line = fileName.nextLine();
n++;
}
int m = line.length();
boolean[][] cells = new boolean[n][m];
// initialize Scanner to read file again
Scanner in = new Scanner(new File("C:/Users/USER/Desktop/hashtag.txt"));
int i=0;
while(in.hasNextLine()){
line = in.nextLine();
for(int j=0; j < line.length(); j++){
char c = line.charAt(j);
if(c == '#'){
cells[i][j] = true;
}
else{
cells[i][j] = false;
}
}
i++;
}
You have many mistakes in code and this approach is definitely wrong, you don't even save values that you read from file inside array. Also this code is simply not how you do it, for reading files where you don't know length of file you want to use Lists where you don't need to specify number of elements that list will take(its possible to do get semi-working solution with arrays but there is no point of learning something that is simply wrong). Before even trying to work with files you should learn more basic things, you don't even initialize your arrays properly, you use string for size and index which is causing those issues you mentioned, another beginner mistake is trying to parse non-integer string to int(you are trying to convert ############ to int which is impossible, you can only use this if you know that string is an integer like 1 or 5 or 1000).
So my answer to your question is to just go slowly and learn basics then add new stuff step by step instead just rushing with it.
It says the [x] and [y] requires an int, but found a string. The same
issue is for cells[finalX][finalY] = true;
I tried parsing i.e. Integer.parseInt(x) however this gets me an
error: Exception in thread "main" java.lang.NumberFormatException: For
input string: "#####################"
One approach you could do is first read the entire file.
Example:
List<String> tempList = new ArrayList<>();
while (fileName.hasNextLine()) {
String line = fileName.nextLine();
tempList.add(line);
}
then you can do this:
boolean[][] cells = new boolean[tempList.size()][tempList.get(0).length()];
note - this solution assumes the length() of each line is the same and the columns of each line is the same.
Also, why do you need to perform this outside the loop?
cells[finalX][finalY] = true;
you should remove that line and let the loop do all the work to determine what's # or ' '. Also, your if condition doesn't seem to be doing the correct operation. Consider implementing this approach and then go on from there.
I'm attempting to write an array inside a for loop that doesn't seem to make any sense with the error.
String[][] userName;
userName = new String[3][4];
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = (String) System.in.read();
}
}
For the line:
userName[x-1][y-1] = (String) System.in.read()
it gives an error:
Incompatible types: int cannot be converted to String
But what in that line is classified as int? The only ones I know are the [x-1][y-1], but they're numbers to find the place in the array, also, I even deleted them, and it still says the same error.
What is classified as int, and how do I fix this error?
because System.in.read() will read bytes will return the value within range of 0-255 so you don't need it , you want to read String then either use Scanner or Streams
Scanner scan =new Scanner(System.in);
for(int x=1; x<= 4; x++) {
for(int y=-1; y <= 3; y++) {
System.out.println("Enter student name for row "+x+"column "+y+" ==>");
userName[x-1][y-1] = scan.read();
}
}
Scanner (import java.util.Scanner)
Scanner scan =new Scanner(System.in);
scan.read(); // read the next word
scan.readLine(); // read the whole line
or
Streams
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String str=br.readLine();
Scanner is easy , comes with lot of functionality link to doc , Streams can be used to read bulk data which sometimes can't be read by scanner
1 for(int x=1; x<= 4; x++)
2 {
3 for(int y=-1; y <= 3; y++)
4 {
5 System.out.println("Enter student name for row "+x+"column "+y+" ==>");
6 userName[x-1][y-1] = (String) System.in.read();
7 }
8 }
Lets split this loop bit by bit.
On line 6, You are taking an Integer input through System.in.read() line, but your array is basically String datatype! So, you cast it to String. however, you cannot really insert int to a string without Integer.toString(System.in.read()). It's the normal way! However, the easiest way would be
userName[x-1][y-1] = "" + System.in.read();
Java reads a line from right to left. So it will take an input and append it to an empty String and then put it inside userName array!.
(Thanks to Pavneet Singh for noticing me)
(Thanks to Erwin Bolwidt for correcting me out. I did not notice it was String!)
Or, you can use Scanner class.
To do that you will need add the following codes.
add the following before your class line (public class)
import java.util.Scanner;
Then when you class starts inside public static void main(..), on the first line or in any convenient line before function, you will write the following line
Scanner sc = new Scanner(System.in);
It initializes the scanner. Then you can use the scanner class!
userName[x-1][y-1] = sc.next();
See through scanner class, you will need to specify the data type you will be providing! So, if you/user provides String or float or boolean value, it will throw an error and program will end/crash! Pretty effective, if you are trying to avoid wrong datatype.
Finally, you probably have an error in your loop declaration on line 3.
You can run the loop from y = -1 but, in Java, array indexes starts from 0. So, there is no index on y - 1 = - 1 - 1 = -2, it will throw an error! To avoid this all you have to do is, declare your loop from y = 1.
for(int y = 1, y <= 3; y++)
Happy programming! Cheers!
Before using System.in.read() you should have done some research on it. The System.in.read() method reads bytes of data from input stream and return the data as integer. So you can only use an integer or a character variable to store the data. String variables cannot store the data returned by the method System.in.read(). And this is the reason why you get the exception
incompatible types: int cannot be converted to String
And also use a try catch block when you are using System.in.read() method.
I am having a problem reading inputs, can anyone help me.
Each line of the input have to Integers: X e Y separated by a space.
12 1
12 3
23 4
9 3
I am using this code in java but is not working, its only reading the first line can anyone help me?
String []f;
String line;
Scanner in=new Scanner(System.in);
while((line=in.nextLine())!=null){
f=line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
if(X<=40 && Y<=40)
metohod(X,Y);
line=in.nextLine();
}
}
You are calling nextLine twice, once in the while, anotherone linha = xxx;
what is linha anyways? Try this
BufferedReader reader = new BufferedReader(...);
while((line = reader.readLine())!=null) {
String[] f = line.split(" ");
int X,Y;
X=Integer.parseInt(f[0]);
Y=Integer.parseInt(f[1]);
}
You're calling one line=in.nextLine() too much, but why not use in.nextInt()? The following should work as expectd:
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
int x = in.nextInt();
int y = in.nextInt();
if(x <= 40 && y <= 40)
method(x, y);
}
(The code is tested, and it reads more than just the first line. Your previous problem could perhaps be the new-line format of the input file.)
Have a look at the scanner API docs.
To debug this you could use the Scanner(File file) constructor instead.
line=in.nextLine();
You are reading the next line and doing nothing with it. If you remove that it should work.
Since you are using Scanner, why don't you just use nextInt() instead of nextLine()? That way you could call nextInt() twice and get the two numbers for each line.
The way you coded it looks as if you are trying to use a BufferedReader instead of a Scanner.
How would you write this code?
This particular question is about a maze game that has an arraylist of occupants which are Explorers (you), Monsters (touching will kill you), and Treasures. The game uses blocks of square objects in which these occupants reside in. The particular thing I want to do is file reading which can export the current configuration of the maze or import them as a txt file.
The specs:
First read in the rows and cols of the Maze to create a Square[][] of the appropriate size. Then construct and read in all the Squares/Occupants.
For Squares, the Maze will first determine that the line starts with "Square". It will then read in the row and col of the Square and use that information to construct a Square object. Finally it will pass the rest of the Scanner to the Square's toObject method so it can initialize itself.
For all other Occupants, the Maze will determine what kind of Occupant it is and construct the appropriate object using the constructor that only takes a Maze. It will not read the row or the col from the Scanner, but simply pass the Scanner on to the toObject method of the newly created object.
This is code that I have so far which could be wrong:
public void readMazeFromFile(String fileName) throws IOException, FileNotFoundException, MazeReadException
{
Scanner fileSc = new Scanner(new File(fileName));
String line = fileSc.nextLine(); //whats on the line, will be overwritten
Scanner lineSc = new Scanner(line);
String temp;
lineSc.useDelimiter(",");
int lineNum = 1; //every time you scan a line out, do lineNum++
int r1, r2, r3, r4, c1, c2, c3, c4;
rows = fileSc.nextInt();
cols = fileSc.nextInt();
Square hi = new Square(rows, cols);
line = fileSc.nextLine();
while ( line != null)
{
line = lineSc.nextLine();
lineSc = new Scanner(line);
if( lineSc.equals("Square"))
{
r1 = lineSc.nextInt();
c1 = lineSc.nextInt();
hi.toObject(lineSc);
}
if (lineSc.equals("Explorer"))
{
explorer.toObject(lineSc);
}
if (lineSc.equals("Treasure"))
{
Treasure.toObject(lineSc);
}
lineNum++;
}
Here is sample output:
5,5
Square,0,0,true,false,false,true,true,true
Square,0,1,true,false,true,false,true,true
Square,0,2,true,false,true,false,false,false
Square,0,3,true,false,false,false,false,false
Square,0,4,true,true,false,false,false,false
Square,1,0,false,false,true,true,true,true
Square,1,1,true,false,true,false,false,false
Square,1,2,true,true,false,false,false,false
Square,1,3,false,true,false,true,false,false
Square,1,4,false,true,false,true,false,false
Square,2,0,true,false,false,true,false,false
Square,2,1,true,false,true,false,false,false
Square,2,2,false,true,false,false,false,false
Square,2,3,false,true,false,true,false,false
Square,2,4,false,true,false,true,false,false
Square,3,0,false,true,false,true,false,false
Square,3,1,true,false,false,true,false,false
Square,3,2,false,true,false,false,false,false
Square,3,3,false,true,true,true,false,false
Square,3,4,false,true,false,true,false,false
Square,4,0,false,true,true,true,false,false
Square,4,1,false,true,true,true,false,false
Square,4,2,false,false,true,true,false,false
Square,4,3,true,false,true,false,false,false
Square,4,4,false,true,true,false,false,false
Explorer,0,0,Scary Name
Treasure,4,4,true
Treasure,2,2,false
Monster,4,4
Monster,3,3
What would you write for this section?
This is a skeleton that you can start with. You really don't need anything more than a Scanner here; it can do everything that you'd need to scan the input and do the conversion, etc. You want to use its next(), nextInt(), nextBoolean() and nextLine() methods.
Scanner in = new Scanner(new File(filename));
in.useDelimiter("\\s+|,");
int rows = in.nextInt();
int cols = in.nextInt();
// construct the array
while (in.hasNext()) {
String type = in.next();
int r = in.nextInt();
int c = in.nextInt();
// read more depending on type
}
Use a
FileReader
on the file and then attach a
StreamTokenizer
to that, far more efficient :)