i am working on a program to read a binary file and update it form a txt file, it was working the all of a sudden it started throwing this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at StockManage.updateInv(StockManage.java:134)
at StockManage.main(StockManage.java:173)
heres the code thats causes the error
try
{
Scanner trans = new Scanner(new File(file));
RandomAccessFile inv = new RandomAccessFile (file2,"rws");
String tempName = "Temp" + (int)(Math.random()*1000000) + ".dat";
RandomAccessFile newInv = new RandomAccessFile (tempName , "rws");
File newFile = new File(tempName);
String transISBN = trans.next();
String author = inv.readUTF();
String title = inv.readUTF();
String iSBN = inv.readUTF();
int amount = inv.readInt();
while (inv.getFilePointer()<=inv.length())
{
boolean empty = true;
while (empty&&trans.hasNext())
{
if (iSBN.compareTo(transISBN)<0)
{
empty = false;
break;
}
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
}
newInv.writeUTF(author);
newInv.writeUTF(title);
newInv.writeUTF(iSBN);
newInv.writeInt(amount);
author = inv.readUTF();
title = inv.readUTF();
iSBN = inv.readUTF();
amount = inv.readInt();
}
im really stuck in this one so any help would be great
Before calling next() on a Scanner object you should call hasNext() to check if there is actually more data to read.
This code part is error-prone:
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
You control trans.hasNext() in the while loop, but you don't before transISBN = trans.next(); put an if(trans.hasNext()) at the top of it and problem will be solved, I guess.
Related
I'm trying to create a csv file with names and ID numbers in order to create individual users. It is also used to identify whether an user has admin status or not (boolean). If I accidentally input a user as an admin when they are not, how can I delete that user or edit his status? I am using an array list. Thanks.
I've included my load method for any clarification needed. I'm new to Stack Overflow so please excuse any formatting errors.
public static void load() throws IOException
{
System.out.println("<<< Loading users >>>");
File userFile = new File("user.csv");
if (!userFile.exists())
{
userFile.createNewFile();
System.out.println("Data file not found.");
add(); // or go and add an item -->addItem()
}
FileReader fr = new FileReader(userFile);
BufferedReader in = new BufferedReader(fr); //read mode
String newfirstName = "";
int newSchool_ID = 0;
String admin = "Y";
String isAdmin = "";
boolean newisAdmin = false;
String temp;
users.clear();
temp = in.readLine(); // read the heading and ignore it
while (in.ready()) // read lines while file has content
{
newisAdmin = false;
temp = in.readLine();
String[] line = temp.split(",");
newfirstName = line[0];
newSchool_ID = Integer.parseInt(line[1]);
if(admin.equals(line[2])){
isAdmin = "Admin";
newisAdmin = true;
}
User newUser = new User(newfirstName, newSchool_ID, newisAdmin);
users.add(newUser);
}
in.close();
System.out.println("User loaded.");
}
Hey there pretty new to Java I have a CSV file that I am scanning line by line (I am assuming) and printing out the details formatted. I keep getting a java.lang.ArrayIndexOutOfBoundsException: 1 what could I be doing wrong?
Here is the CSV file contents.
1,Mazda CX-9,7,Automatic,Premium,150
2,VW Golf,5,Automatic,Standard,59
3,Toyota Corolla,5,Automatic,Premium,55
4,VW Tiguan,7,Automatic,Premium,110
5,Ford Falcon,5,Manual,Standard,60
String fileName = "CarList.CSV";
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
carsAvailableCount++;
String line = input.nextLine();
int lenght = line.length();
String fields[] = line.split(",");
String carNo = fields[0];
String carName = fields[1];
String seats = fields[2];
String transmission = fields[3];
String carType = fields[4];
String rate = fields[5];
System.out.format("%-9s%-9s%-9s%-9s%-9s%-9s\n", carNo, carName, seats, transmission, carType, rate);
}
Figured out the problem haha, my CSV file had empty lines below my last entry. Cheers everyone.
Hey I just started learning how to code. I am using netbeans and I want to transfer some data from a txt.file into an array in java. This might be a really simple fix but i just cant see whats wrong
This is the data in the txt.file:
58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds
This is the code I am using however smthg is wrong with the last line of code:
int points = 0;
String name = "";
String a = "";
String b = "";
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
}
System.out.println(Arrays.toString(Questions));
}
}
This is the error I am getting:
error: cannot find symbol
System.out.println(Arrays.toString(Questions));
Thx soooo much guys.
You can also use the below code if you just want to print the data:
Files.readAllLines(Paths.get("questions.txt")).forEach(line -> {
System.out.println(Arrays.toString(line.split("_")));
});
Output is :
[58, hello, sad, happy]
[685, dhejdho, sahdfihsf, hasfi]
[544654, fhokdf, dasfjisod, fhdihds]
The correct version of your code should be like the below (you must access the variable Question in the declared scope by moving println into end of while loop) :
// definitions...
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
System.out.println(Arrays.toString(Questions));
}
}
}
I want to counter the lines of the file and in the second pass i want to take every single line and manipulating it. It doesn't have a compilation error but it can't go inside the second while ((line = br.readLine()) != null) .
Is there a different way to get the lines(movies) of the file and storing in an array ?
BufferedReader br = null;
try { // try to read the file
br = new BufferedReader(new FileReader("movies.txt"));
String line;
int numberOfMovies = 0;
while ((line = br.readLine()) != null) {
numberOfMovies++;
}
Movie[] movies = new Movie[numberOfMovies]; // store in a Movie
// array every movie of
// the file
String title = "";
int id = 0;
int likes = 0;
int icounter = 0; // count to create new movie for each line
while ((line = br.readLine()) != null) {
line = line.trim();
line = line.replaceAll("/t", "");
line = line.toLowerCase();
String[] tokens = line.split(" "); // store every token in a
// string array
id = Integer.parseInt(tokens[0]);
likes = Integer.parseInt(tokens[tokens.length]);
for (int i = 1; i < tokens.length; i++) {
title = title + " " + tokens[i];
}
movies[icounter] = new Movie(id, title, likes);
icounter++;
}
} catch (IOException e) {
e.printStackTrace();
}
Simplest way would be to reset br again.
try { // try to read the file
br = new BufferedReader(new FileReader("movies.txt"));
String line; int numberOfMovies = 0;
while (br.hasNextLine()){
numberOfMovies++;
}
br.close();
Movie[] movies = new Movie[numberOfMovies];
// store in a Movie
// array every movie of
// the file
String title = "";
int id = 0;
int likes = 0;
int icounter = 0;
// count to create new movie for each line
br = new BufferedReader(new FileReader("movies.txt"));
while ((br.hasNextLine()) {
line = line.trim();
line = line.replaceAll("/t", "");
line = line.toLowerCase();
String[] tokens = line.split(" ");
// store every token in a
// string array
id = Integer.parseInt(tokens[0]);
likes = Integer.parseInt(tokens[tokens.length]);
for (int i = 1; i < tokens.length; i++) {
title = title + " " + tokens[i];
}
movies[icounter] = new Movie(id, title, likes);
icounter++;
}
} catch (IOException e) { e.printStackTrace(); }
I changed br.nextLine() != null to br.hasNextLine() because it's shorter and more appropriate in this case. Plus it won't consume a line.
There are two things here:
InputStreams and Readers are one-shot structures: once you've read them to the end, you either need to explicitly rewind them (if they support rewinding), or you need to close them (always close your streams and readers!) and open a new one.
However in this case the two passes are completely unnecessary, just use a dynamically growing structure to collect your Movie objects instead of arrays: an ArrayList for example.
Firstly, there is no need to read the file twice.
Secondly, why don't you use the java.nio.file.Files class to read your file.
It has a method readAllLines(Path path, Charset cs) that gives you back a List<String>.
Then if you want to know how many lines just call the size() method on the list and you can use the list to construct the Movie objects.
List<Movie> movieList = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("movies.txt"), Charset.defaultCharset())) {
// Construct your Movie object from each individual line and add to the list of Movies
movieList.add(new Movie(id, title, likes));
}
The use of the Files class also reduces your boilerplate code as it will handle closing the resource when it has completed reading meaning you will not need a finally block to close anything.
If you use the same Reader, everything is already read once you reach the second loop.
Close the first Reader, then create another one to read a second time.
You are running through the file with the BufferedReader, until the nextline points towards null. As your BufferedReader IS null, it won't even enter the second while((line = br.readline) != null), as the first read line is null.
Try getting a new BufferedReader. something like this:
...
int id = 0;
int likes = 0;
int icounter = 0;
br = new BufferedReader(new FileReader("movies.txt")) //Re-initialize the br to point
//onto the first line again
while ((line = br.readLine()) != null)
...
EDIT:
Close the reader first..
This is a combination of a couple of other answers already on this post, but this is how I would go about rewriting your code to populate a List. This doubly solves the problem of 1) needing to read the file twice 2) removing the boilerplate around using BufferedReader while using Java8 Streams to make the initializing of your List as concise as possible:
private static class Movie {
private Movie(int id, String title, int likes) {
//TODO: set your instance state here
}
}
private static Movie movieFromFileLine(String line) {
line = line.trim();
line = line.replaceAll("/t", "");
line = line.toLowerCase();
String[] tokens = line.split(" "); // store every token in a
String title = "";
int id = Integer.parseInt(tokens[0]);
int likes = Integer.parseInt(tokens[tokens.length]);
for (int i = 1; i < tokens.length; i++) {
title = title + " " + tokens[i];
}
return new Movie(id, title, likes);
}
public static void main(String[] args) throws IOException {
List<Movie> movies = Files.readAllLines(Paths.get("movies.txt"), Charset.defaultCharset()).stream().map
(App::movieFromFileLine).collect(Collectors.toList());
//TODO: Make some magic with your list of Movies
}
For cases where you absolutely need to read a source (file, URL, or other) twice, then you need to be aware that it is quite possible for the contents to change between the first and second readings and be prepared to handle those differences.
If you can make a reasonable assumption that the content of the source will fit in to memory and your code fully expects to work on multiple instances of Readers/InputStreams, you may first consider using an appropriate IOUtils.copy method from commons-io to read the contents of the source and copy it to a ByteArrayOutputStream to create a byte[] that can be re-read over and over again.
I wrote a program to read a file. It reads the file correctly. I tested using print statements. But after reading the last line in the file, the program doesn't stop. It goes into an infinite loop. I am guessing that my while loop keeps reading blank characters as the next line. I don't know how to fix it.
If I put a break in the else part, it just reads the first line and breaks out of the while loop. I am not sure why.
Please help me out.
Here is the code :
public static void InterpretMessageFromFile() throws FileNotFoundException{
File inputfile = new File("FilePath");
Scanner reader = new Scanner(inputfile);
try
{
while (reader.hasNextLine())
{
//if the type of order is add order to existing Order Book
if (reader.hasNext("A")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
//int id = Integer.parseInt(retrieve_id ,2); // for binary file
String or_side = reader.next();
String retrieve_share = reader.next();
int share = Integer.parseInt(retrieve_share);
// int share = Integer.parseInt(retrieve_share, 2); //for binary file
String retrieve_price = reader.next();
int price = Integer.parseInt(retrieve_price);
//int price = Integer.parseInt(retrieve_price, 2); //for binary file
System.out.println("Add Order : Id is " + id );
AddOrderToExistingBook.AddNewOrder(id, ts, or_side, share, price);
}
//if it is cancel order
else if (reader.hasNext("X")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts);
//int ts = Integer.parseInt(retrieve_ts, 2); //for binary file
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id);
System.out.println("Cancel Order : Id is " + id + " time stamp is : " + ts );
//int id = Integer.parseInt(retrieve_id, 2); //for binary file
//String retrieve_share = reader.next();
// int share = Integer.parseInt(retrieve_share, 2); // need to add back later, removing it for testing purposes
CancelOrder.CancelPartOfOrder(id, ts);
}
//if it is delete order
else if (reader.hasNext("D")){
reader.next();
String retrieve_ts = reader.next();
int ts = Integer.parseInt(retrieve_ts, 2);
String retrieve_id = reader.next();
int id = Integer.parseInt(retrieve_id, 2);
DeleteOrder.DeleteOrderFromBook(id, ts);
}
else{
// unexpected token.
// basically log as info and ignore.
}
}
}
finally
{
reader.close();
}
}
When handling file reading operations, it is always good to check couple of conditions -
1) Does the file has next line? 2) Is the next line not null.
while (reader.hasNextLine() && (line = reader.nextLine()) != null)
And then you can use this String line in your code.
In you code, although you are getting the next value by reader.next(), It does not advance the pointer. That is the reason the loop never exits.
Ref: Scanner
The last else block does not actually consume the line. Therefore if you've got any characters after the last line of real data in your input the program will always have a next line. Try consuming the file one line at a time and then using String.split() to get the individual tokens in each line. This guarantees that you will consume every line in the file.