Something's wrong with my Scanner and my file - java

Whenever I run this method, it produces an error saying that there is no line. The file (inv.txt) is a 1 on 25 lines, So 25 ones, each on a seperate line.
public class Inventory
{
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;
public void addItem(int item, int slot)
{
int i = 1;
writethis = new StringBuilder();
Scanner scan;
try
{
scan = new Scanner(inventory);
if (scan.hasNextLine())
{
while (i < slot)
writethis.append(scan.nextLine()); // This is where it says the
// error is. For reference,
// slot is 2. It may somehow
// be making an infinite loop,
// but I don't know why it
// would.
scan.nextLine();
writethis.append(item);
while (i < 24)
writethis.append(scan.nextLine());
System.out.println(writethis.toString());
scan.close();
}
try
{
write = new FileWriter(inventory);
write.write(writethis.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}

Could this be due to the fact that the instance variable i is never incremented?
I would also close the data streams in a finally block.

Related

How to rerun try block upon catching an InputMismatchException? [duplicate]

I am creating a small algorithm and this is a part of it.
If the user enters non integer values, I want to output a message and let the user enter a number again:
boolean wenttocatch;
do
{
try
{
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
}
catch (Exception e)
{
wenttocatch=true;
System.out.println("xx");
}
} while (wenttocatch==true);
I am getting a never ending loop and I can't figure out why.
How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?
Update
When I am printing the exception I get 'InputMismatchException', what should I do?
The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc. Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.
boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);
do {
try {
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
} catch (InputMismatchException e) {
sc.next();
wenttocatch = true;
System.out.println("xx");
}
} while (wenttocatch == true);
You dont have to do a try catch. This code will do the trick for you :
public static void main(String[] args) {
boolean wenttocatch = false;
Scanner scan = new Scanner(System.in);
int number_of_rigons = 0;
do{
System.out.print("Enter a number : ");
if(scan.hasNextInt()){
number_of_rigons = scan.nextInt();
wenttocatch = true;
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(!wenttocatch);
}
Anytime you get an exception, wenttocatch is set to true and the program will be stuck in an infinite loop. As long as you don't get the exception you'll not get an infinite loop.
The logic if sc.nextInt() causing the error is this
1) wenttocatch is set to false
2) sc.nextInt() throws error
3) wenttocatch is set to true
4) repeat[because wenttocatch is true]
To solve this set wentocatch=false in catch statement
catch (Exception e) {
wenttocatch=false;
System.out.println("xx");
}
if you are doing more than you show here, use a counter[if your counting or a boolean if you are not], but unless you are doing more, do the first thing above
boolean wenttocatch;
int count = 0;
do{
try {
wenttocatch=false;
number_of_rigons=sc.nextInt(); // sc is an object of scanner class
} catch (Exception e) {
count++;
wenttocatch=true;
System.out.println("xx");
}
}while(wenttocatch==true && count < 1);
Answer Comment:
I think you want to get ints until a user doesn't enter anymore. Depending on your input one way of doing that is this
int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
//do something
}
you simply can use the hasNext(); method in java, instead of try and catch.
The hasNext() is a method of Java Scanner class that returns true if this scanner has another token in its input.
String[] stringArray = new String[lines];
int i = 0;
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String data=sc.nextLine();
stringArray[i] = data;
i++;
}
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("Error opening file.");
throw new FileNotFoundException();
} catch (NoSuchElementException e) {
System.err.println("Error in file record structure");
throw new NoSuchElementException();
} catch (Exception e) {
e.printStackTrace();
}
/*added the scanner declaration inside try im new on programming its worked for me but I don't know if its good practice
*/ :
boolean wenttocatch;
do
{
try
{
Scanner sc=new Scanner(System.in);
wenttocoatch = false;
number_of_rigons = sc.nextInt();
}
catch (Exception e)
{
wenttocatch=true;
System.out.println("xx");
}
} while (wenttocatch==true);
....
try {
....
} catch (Exception e) {
sc.next();
wenttocatch=true;
System.out.println("xx");
}

For java I/O I am reading from a file but when I get the data and try to send it to another method it gives me a null pointer error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to take integers from a file and put put them into an array but it keeps giving me a null pointer error. The text file is 100 lines with a single integer on each. When I debug it the file is being read and the proper integer is being stored but when I try to send it to my popBArray method it doesn't work.
public void readBoardFile(String filename) {
try {
Scanner filescanner = new Scanner(new File(filename));
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine();
int num = Integer.parseInt(line);
popBarray(num);
}
filescanner.close();
} catch (IOException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
}
int c = 0;
public void popBarray(int sent) {
BoardA[c] = sent;
c++;
}
You may not initialize BoardA.
The code may help you.
public void readBoardFile(String filename) {
try {
Scanner filescanner = new Scanner(new File(filename));
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine();
int num = Integer.parseInt(line);
popBarray(num);
}
filescanner.close();
}catch (IOException e){
System.out.println(e);
}catch (Exception e){
System.out.println(e);
}
}
int c = 0;
public int[] BoardA = new int[100]; // initialize BoardA.
public void popBarray(int sent) {
BoardA[c] = sent;
c++;
}

Reading integers from text file

I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
The error I get is: NoSuchElementException.
The file looks like this:
N,X1,Y1,X2,Y2,X3,Y3
While n equals 3 in this example.
I call this method a in the main method like this:
readFromFile("file.txt");
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Writing and reading int from file after loop

I'm writing an application that is supposed to act like a cafe clip card. In other words, for every n:th (10 in my case) coffee that a customer purchases, he/she is awarded a free beverage. So, I'm quite done with the loop and I've been working on writing and reading from a file since I need the program to remember where it last left off in order for the customer to be able to close the application once he/she has been in the store. However, I'm having a difficult time figuring out how to write and read from a file, the code I have doesn't seem to output any .txt file. I need the code to have a closing condition, and upon entering this condition, it should write the "count" to a .txt file, and shut down. Once the program is being run the next time it should read from this .txt file so it knows where the count is at.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("countStorage.txt"))));
bw.write(count);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(newInputStreamReader(newFileInputStream(new File("countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
I see a few problems here. In your readFromFile() method, put a space after the keyword new. I also suggest putting a an absolute path for now (for debugging):
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
In your saveToFile() method, the constructor is wrong. Also put the full path to the file here:
bw = new BufferedWriter(new FileWriter("C:\\Temp\\countStorage.txt"));
Finally, in your saveToFile() method, write the count as a String. Writing it as an int refers to the Unicode character:
bw.write(Integer.toString(count)); //updated per Hunter McMillen
And invoke it...
FelixNeww f = new FelixNeww();
f.saveToFile(44);
System.out.println(f.readFromFile());
You need to invoke readFromFile or saveToFile in the place needed in order to become executed.
I suggest that you call readFromFile on the beginning of the Main method, use its returning contents, and saveToFile in the loop whenever the desired state changes and it needs to be saved.

Java Compiler - Load Method

So I have been working on a java project where the goal is to create a virtual computer. So I am basically done but with one problem. I have created a compiler which translates a txt document with assembly code in it and my compiler has created a new-file with this code written as machine executable ints. But now I need to write a load method that reads these ints and runs the program but I am having difficulty doing this. Any help is much appreciated....also this is not homework if you are thinking this. The project was simply to make a compiler and now I am trying to complete it for my own interest. Thanks.
Here is what I have so far for load:
public void load(String newfile) throws FileNotFoundException
{
try{
File file = new File(newfile);
FileInputStream fs = new FileInputStream(file);
DataInputStream dos = new DataInputStream(fs);
dos.readInt();
dos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Ok here is the part of the Compiler that does the writeInts:
public void SecondPass(SymbolList symbolTable, String filename){
try {
int dc = 99;
//Open file for reading
File file = new File(filename);
Scanner scan = new Scanner(file);
//Make filename of new executable file
String newfile = makeFilename(filename);
//Open Output Stream for writing new file.
FileOutputStream fs = new FileOutputStream(newfile);
DataOutputStream dos = new DataOutputStream(fs);
//Read First line. Split line by Spaces into linearray.
String line = scan.nextLine();
String[] linearray = line.split(" ");
while(line!=null){
if(!linearray[0].equals("REM")){
int inst = 0, opcode, loc;
if(isInstruction(linearray[0])){
opcode = getOpcode(linearray[0]);
loc = symbolTable.searchName(linearray[1]).getMemloc();
inst = (opcode*100)+loc;
} else if(!isInstruction(linearray[0])){
if(isInstruction(linearray[1])){
opcode = getOpcode(linearray[1]);
if(linearray[1].equals("STOP"))
inst=0000;
else {
loc = symbolTable.searchName(linearray[2]).getMemloc();
inst = (opcode*100)+loc;
}
}
if(linearray[1].equals("DC"))
dc--;
}
dos.writeInt(inst);
System.out.println(" inst is being written as:" + inst);
}
try{
line = scan.nextLine();
}
catch(NoSuchElementException e){
line = null;
break;
}
linearray = line.split(" ");
}
scan.close();
for(int i=lc; i<=dc; i++){
dos.writeInt(0);
}
for(int i = dc+1; i < 100; i++)
{
dos.writeInt(symbolTable.searchLocation(i).getValue());
}
dos.close();
fs.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So what I have done is write a file in txt like:
IN X
In Y
SUB X
STO Y
OUT Y
DC: X 0
DC: Y 0
And I wrote a compiler that has now converted this file into machine code so I have created a file for example called program.txt.ex and it contains a bunch of ####### or machine code and I did this using the SecondPass code above and now I need to write a load method that will allow me to load and run this file.
Here is my Run method
public void run(String filename) throws IOException
{
if (mem == null)
System.out.println("mem null");
if (filename == null)
System.out.println("filename null");
mem.loadFromFile(filename);
cpu.reset();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
while (!cpu.stop())
{
cpu.decode();
if (cpu.OutFlag())
OutPut.display(mem.read(cpu.getMAR()));
if (cpu.InFlag())
mem.write(cpu.getMDR(),in.getInt());
if (cpu.StoreFlag())
{
mem.write(cpu.getMAR(),in.getInt());
cpu.getMDR();
}
else
{
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.execute();
cpu.fetch();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
}
}
}
The Run Method:
public void run(int mem)
{
cpu.reset();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
while (!cpu.stop())
{
cpu.decode();
if (cpu.OutFlag())
OutPut.display(mem.read(cpu.getMAR()));
if (cpu.InFlag())
mem.write(cpu.getMDR(),in.getInt());
if (cpu.StoreFlag())
{
mem.write(cpu.getMAR(),in.getInt());
cpu.getMDR();
}
else
{
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.execute();
cpu.fetch();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
}
}
}
I notice that your loader does a single
dos.readInt();
...which will read a single integer value from your file. What you probably want to do is create a loop that reads ints until you hit the end-of-file on dos (which might more aptly be named dis, no?). You could add those ints to a dynamic container like an ArrayList, which will grow with every element you stuff into it. Once done loading, you can use toArray to copy all those ints to an array of the appropriate size.
If seems that you need to load the whole file in memory before starting execution, so it would go:
public int[] load(String newfile) throws FileNotFoundException
{
int mem[] = new int[100];
try {
File file = new File(newfile);
FileInputStream fs = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fs);
for (int i = 0; i < mem.length; ++i) {
mem[i] = dis.readInt();
}
dos.readInt();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
return mem;
}
void run(int mem[]) {
// now execute code
int pc = 0;
loop: while (true) {
int inst = mem[pc++];
int opcode = inst/100;
int loc = inst%100;
switch (opcode) {
case OpCode.STOP:
break loop;
case OpCode.IN:
...
}
}
}

Categories

Resources