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.
Related
I'm trying to read a String and then Integers or Strings using Scanner:
public class Main {
public static void main (String[] args){
String[] StringList;
Integer[] IntegerList;
ArrayList<String> auxS = new ArrayList<>();
ArrayList<Integer> auxI = new ArrayList<>();
String order; int ord=-1;
Scanner scan = new Scanner(System.in);
order = scan.nextLine();
//do something with order
while(scan.hasNextLine()){
if(scan.hasNextInt()){
auxI.add(scan.nextInt());
}
else if(!scan.nextLine().isEmpty()){
auxS.add(scan.nextLine());
}else{ //I've tried using another scan. methods to get to this point
scan.next();
break;
}
}
}
}
As you can see, I first read a String and store it in "order", then I want to keep reading until EOF or user enters "Enter" or anything else non-specific such as "write 'exit' " or something like that.
I've tried using scan.hasNext, hasNextLine, and other combinations involving the last else but none of them worked.
If the input is:
>>THIS WILL BE STORED IN ORDER<<
123
321
213
231
312
<enter>
I want it to stop when nothing has been entered as in the last line. It is important to store the Integers or Strings in their own ArrayLists, as I use it later and I need to identify the type of each entered data (that's why I use hasNextInt inside the while loop).
Generally, just don't use .nextLine(), it is confusing and rarely does what you want. If you want to read entire lines as a single item, update the scanner's delimiter; change it from the default 'any sequence of whitespace' to 'a single newline': scanner.useDelimiter("\r?\n"); will do that (run that immediately after making a scanner). To read a line, use any of the .next() methods (but not .nextLine()): Want an int? call .nextInt(). Want any string? Call .next(), etcetera.
then split up your if/elseif block. An empty line is still a string, just, an empty one:
if (scanner.hasNextInt()) {
// deal with ints
} else {
String text = scanner.next();
if (!text.isEmpty()) {
// deal with strings
} else {
// deal with a blank line
}
}
NB: Once you stop using .nextLine(), you don't have to throw out semi-random .nextLine() calls to 'clear the buffer' or whatnot. That annoyance just goes away, which is one of the many reasons why you should just forget about nextLine. Generally, for scanners, either use only .nextLine(), or don't ever use .nextLine(), and things work out much better.
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
Okay so I'm having a slight problem with scanner advancing an extra line. I have a file that has many lines containing integers each separated by one space. Somewhere in the file there is a line with no integers and just the word "done".
When done is found we exit the loop and print out the largest prime integer that is less than each given integer in each line(if integer is already prime do nothing to it). We do this all the way up until the line with "done".
My problem: lets say the file contains 6 lines and on the 6th line is the word done. My output would skip lines 1, 3 and 5. It would only return the correct values for line 2 and 4.
Here's a snippet of code where I read the values in:
Scanner in = new Scanner(
new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
while(in.nextLine() != "done"){
String[] arr = in.nextLine().split(" ");
Now I sense the problem is that the nextLine call in my loop advances the line and then the nextline.split call also advances the line. Thus, all odd number lines will be lost. Would there be another way to check for "done" without advancing a line or is there a possible command I could call to somehow reset the scanner back to the start of the loop?
The problem is you have 2 calls to nextLine() try something like this
String line = in.nextLine();
while (!"done".equals(line)) {
String[] arr = line.split(" ");
// Process the line
if (!in.hasNextLine()) {
// Error reached end of file without finding done
}
line = in.nextLine();
}
Also note I fixed the check for "done" you should be using equals().
I think you are looking for this
while(in.hasNextLine()){
String str = in.nextLine();
if(str.trim().equals("done"){
break;
}else{
String[] arr = str.split("\\s+");
//then do whatever you want to do
}
}
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.
I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.
Here is what I have:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while ( line != null )
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
Basically, it finds the last name, first name and office number in a .csv file and prints them out.
When I compile I don't get any errors but when I run it I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.
Any ideas?
Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.
Let's work by example, what issues you have with your code.
Eg: line: Overflow,stack
{ length: 14 }
Taking your program statements line by line -
int positionOfComma = line.indexOf(","); // returns 9
lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1
Now lastName has Overflow. positionOfComma has 9.
line = line.substring(positionOfComma+1);
Now line has stack.
firstName = line.substring(0,positionOfComma);
Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.
From JavaDoc:
(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.
In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.
You need to:
a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)
b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.
A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)
You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.
int positionOfComma = line.indexOf(",");
this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:
int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
positionOfComma = line.indexOf(",");
}
You do have to do lots of checking of things sometimes especially when the data is whacked :(
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)