I am trying to create a program that generates chutes and ladders onto 2D array board that is of size 10X10. In order to generate these chutes and ladders, I had to create a method called readBoard that basically reads a written file (myBoard.csv) and translates the written information into positions and place the chutes and ladders onto the 2D array board accordingly.
The program compiles but when I run it there is this error:
java.lang.ArrayIndexOutOfBoundsException: 1
at ChutesAndLadders.readBoard(ChutesAndLadders.java:41)
at TestFile.main(TestFile.java:13)
My impression was that perhaps my written file had additional spaces that I didn't see that's why it's telling me I'm out of bound. However, I checked the written file and it looks fine. If you could provide some insight into this problem, that would be great. Thanks in advance!
Here is my getBoardmethod:
public void readBoard(String filename)throws Exception
{
Scanner s=new Scanner(new File(filename));
s.nextInt();
while (s.hasNext())
{
String line=s.nextLine();
String[]singleSplit=line.split(",");
String cellType=singleSplit[0];
int row=Integer.parseInt(singleSplit[1]);
int col=Integer.parseInt(singleSplit[2]);
if (cellType.equals("Chute"))
board[row][col]=new Chute();
else
board[row][col]=new Ladder();
}
}
and here is my written file (type,row,column):
29
Chute,1,0
Chute,2,0
Chute,3,0
Chute,4,0
Chute,5,0
Chute,6,0
Chute,7,0
Chute,8,0
Chute,9,0
Chute,0,1
Chute,0,2
Chute,0,3
Chute,9,1
Chute,9,2
Chute,9,3
Ladder,0,5
Ladder,1,5
Ladder,2,5
Ladder,3,5
Ladder,4,5
Ladder,5,5
Ladder,6,5
Ladder,7,5
Ladder,8,5
Ladder,9,5
Ladder,9,6
Ladder,9,7
Ladder,9,8
Ladder,9,9
Replace s.nextInt(); with s.nextLine(); to read the first line from the file. If you need that value, you can do Integer.parseInt() on it.
nextInt() doesn't change the line counter in Scanner, so nextLine() call will return the rest of the line you're currently at. To avoid that you need to explicitly change line counter by doing an extra nextLine() call after your nextInt():
s.nextInt();
s.nextLine();
From Scanner.nextLine API doc:
This method returns the rest of the current line, excluding any line
separator at the end.
So in your code the first call to nextLine() simply returns an empty string.
Related
I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.
char input = scanner.nextLine().charAt(0);
What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.
char input = scanner.nextLine().charAt(0);
First thing that's unclear is what Object type is scanner?
But for now I'll assume scanner is the Scanner object from Java.util.Scanner
If that's the case scanner.nextLine() actually returns a String.
String has a charAt() method that will allow you to pick out a character anywhere in the string.
However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.
scanner.next() will give you the next word in the line.
If the line contained "Hello World"
scanner.next().charAt(0) would return the character 'H'.
the next call of scanner.next().charAt(0) would then return the character 'W'
public static void main(String[] args) {
boolean finished = false;
ArrayList<Character> firstLetters = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (!finished) {
firstLetters.add(scanner.next().charAt(0));
}
}
The above code sample might give you the behavior you're looking for.
Please note that the while loop will run forever until finished becomes true.
Your program will have to decide when to set finished to true.
AND here's a couple of links about Java's Scanner class
tutorials point
Java Docs
I am trying to read multiple line from a file using java scanner. Each line has strings separated using comma, but there is no comma at the end of line. My text file contains value like below
98792203000000005091,89065012012341234100000000000167,084952103900000015
98792203000000005091,89065012012341234100000000000167,084952103900000015
The scanner is throwing a no element exception, it works fine if I add a comma t the end of line, but the original file will not have a comma. How do I make work
Scanner sc = new Scanner(outPutFile);
int outputDataStart = Integer.parseInt(outputDataStartLine);
skipLines(sc, outputDataStart);
sc.useDelimiter(",");
while(sc.hasNext())
{
OutputVariables outputVariables = new OutputVariables();
outputVariables.setIccid(sc.next());
outputVariables.setImsi(sc.next());
outputVariables.setKey(sc.next());
outputVariables.setPIN1(sc.next());
outputVariables.setPUK1(sc.next());
outputVariables.setPIN2(sc.next());
outputVariables.setPUK2(sc.next());
outputVariables.setPINAdm(sc.next());
outputVariables.setAccount(sc.next());
outputVariables.setKIC(sc.next());
outputVariables.setKID(sc.next());
outputVariables.setKIK(sc.next());
outputVariables.setOPCKey(sc.next());
OutputVariableList.add(outputVariables);
}
Insteard of using sc.useDelimiter(",") use sc.useDelimiter(",|\\n") it would break by both , and new line
You're asking the scanner to parse more values from a line of text than there are values. This is happening because you're calling next() without first checking hasNext(). Since you've told it to use the comma as the delimeter, it's hitting the end of the line continuing on to the next line until it finds the next comma.
Consider this CSV:
A,B,C,D
If you call next() after you parse the "D", the scanner will throw a NoSuchElementException.
It is not clear what you're attempting to do. If you're attempting to convert what is effectively a CSV into an object, then your best bet would be to use the Scanner to read each line, and then a String.split() call to split that line into parts.
If you're trying to parse multiple lines into an object, you'll of course need to figure out where your boundary is -- every fifteen comma separated values? every three lines? -- and apply that logic while collecting your segments.
As a simplified example, consider this collection of lines:
A,B,C,D
E,F,G,H
I,J,K
You would first use the Scanner to read line-by-line, and then use split each line apart and create the individual objects. Notice the last line is malformed -- you'll need to trap for that and catch it to avoid the NoSuchElementException.
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
String line = sc.next();
String[] parts = line.split(",");
if(parts.length != 4) {
System.err.println("Invalid line: " + line);
continue; // skip this record, it is bad
}
// create your object here from parts
Pojo example = new Pojo(parts[0], parts[1], parts[2], parts[3]);
// etc
}
Alternatively if you're just trying to create a single massive object -- eg all lines belong to the same record -- you could tell it to consider a newline as a delimeter in addition to a comma. That way, after you hit the last comma in the first line, you would call next() and it would parse until the end of the line; and then when you called next() again, it would parse starting on the next line until it reached a comma or the end of the line, whichever came first.
I suggest you to use BufferedReader
it has a method named readLine()
first read a String then through the string.split(",") you can get the array of String
I am a beiggner in java programming and i have a problem i want to get input from user in one line such as in c++
in c++ if i want to make a calculator i make 2 variable for example a band third is op and make user input them by
cin>>a>>op>>b;
if (op=='+')
{
cout<<a+b<<endl;
}
and so on how to make that in Java ?
i make a try in java but i get Error
and one more question how to make user input a char i try char a=in.next(); but get error so i make it string
code java
Scanner in=new Scanner(System.in);
int a=in.nextInt();
String op=in.nextLine();
int b=in.nextInt();
if (op=="+")
{
System.out.println(a+b);
}
else if (op=="-")
{
System.out.println(a-b);
}
.........
First of all, in Java you compare String with a.equals(b), in you example it would be op.equals("+"). And also, after reading a line it have the line break character (\n), so you should remove it to avoid problems. Remove it using String op = in.nextLine().replace("\n", "");.
And answering the how to read a character part, you can use char op = reader.next().charAt(0)
I have written the following code to print file content and print the number of character and words from file
import java.io.*;
import java.util.*;
class Ass53
{
public static void main(String args[]) throws Exception
{
File file=new File("sample.txt");
Scanner sc=new Scanner(new FileInputStream(file));
String line,line1;
int count1=0;
int count=0;
/*Loop for printing contents of file*/
while(sc.hasNextLine())
{
line=sc.nextLine();
System.out.println(line);
}
/*loop for counting number of character in file*/
while(sc.hasNext())
{
line1=sc.next();
for(int i=1;i<=line1.length();i++)
count1++;
}
System.out.println(count1);
/*loop for counting number of words in a file*/
while(sc.hasNext())
{
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
}
The problem is that only first while loop is executing.I guess the reason may be the sc.nextLine for first while loop.After first while loop sc points to nothing i guess?.
Is there any way to fix it?
I want that my other while loop also work
Every time you are doing nextLine() you are advancing the scanner past the current line. When the first loop is over, you are at the end of the file and there is nothing to scan.
A solution would be to recreate the scanner before each loop. Just repeat this before second and third while:
sc=new Scanner(new FileInputStream(file));
Another solution would involve more work but is more elegant: use a single loop to store all lines in a List<String>, then analyse all lines to count words and characters.
The first loop say "until I run out of lines in the file, read the line and print it." Then the second loop looks for more characters in the file, and of course there's nothing there.
One option is to reset the scanner before each loop. Before each loop after the first, just close and discard the scanner, and create a new one.
There's a better way, though. You can walk through the file character-by-character (e.g. with a BufferedReader), and increment the character count on each character, and the newline count on each newline character. Don't forget to account for files that don't end with a newline. Only one loop is required, and you've calculated both the total character count and the line count.
You need to set your sc back to the beginning of the stream after you're done looping over it each time.
I won't post the code because this looks like homework, and I'm guessing the class name Ass53 is "Assignment53". It shouldn't be too hard to look up and figure out how to set the stream back to the beginning.
Of you could try to combine this into a single loop, because as it stands right now, you're actually reading the same file 3 times. It might not be that bad if it's a small file, but if it's a larger file that would be slow.
I have an array with types and numbers and when printing this is the outcome:
car:1 car:2 car:3 boat:1 boat:2 boat:3 plane:1 plane:2 plane:3
I am looking for a way to determine when the type changes, and then make a new line. which means to print a "\n" after car:3 (and boat:3) so all the vehicles are on their own row.
I am printing all these items with a for-loop like this:
for(Types filename: TypeTable)
{
Scanner s;
s = new Scanner(filename.toString());
while (s.hasNext())
{
System.out.print(s.nextLine()+ " ");
}
and I guess I am in need for some local loop and to save the first type in some temp variable and in a loop print a newline when it changes, but I am kinda stuck.
edit2:
after taking a break and then coming back i managed to fix the problem, and even without having a blank line in beginning. the problem was that i had to define oldTransport in main-class :) ofc you couldnt have known how my structure was. thank you hovercraft of eel :)
Rather than printing the line via System.out.print(...) get the line and put it into a variable. Split it via the String#split(...) method, and compare the first part obtained (the String in the [0] spot of the array obtained from split) with the previous String's first part (that was also saved to a variable). If different, make a new line before printing the line out.
Also, if you are going to extract a nextLine() from the scanner, check for a hasNextLine(), not hasNext().
In pseudocode
String oldTransportation gets assigned ""
while the scanner has a next line
String variable line gets scanner's next line
String array called tokens gets this line split on ":"
String newTransportation gets the [0] item in the tokens array
Check if newTransportation equals(...) oldTransportation,
if different, call System.out.println().
print the line variable String
oldTransportation gets assigned newTransportation
end while scanner...
Lets keep track of the previous type.
String lastTypeName = "";
for(Types filename: TypeTable) {
if(!lastTypeName.equals(filename.toString()) {
lastTypeName = filename.toString();
System.out.println();
}
Scanner s = new Scanner(filename.toString());
while (s.hasNext()) {
System.out.print(s.nextLine()+ " ");
}
s.close();
}
A line break will get printed before the first line, but maybe that is not a problem.