To be fair, I'm not getting these exceptions but merely trying to find a away to cover these exceptions. The exceptions are NosuchElementException and NumberFormatException.
Note: This programs works perfectly because the txt file is fine. However, introduce anything that is not a number and it will fail.
Here is the main class where the problem could occur:
BankReader.java
package bankreader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BankReader
{
public static void main(String[] args)
{
BankReader reader = new BankReader();
Scanner scan = new Scanner(System.in);
String fileName = "";
boolean finished = false;
while(!finished)
{
try
{
System.out.print("Enter the name of the file: ");
fileName = scan.nextLine();
scan = reader.checkFile(fileName, scan);
reader.readFile(scan);
finished = true;
}
catch(IOException ex)
{
System.out.print("\nThis file does not exist or had");
System.out.println(" characters that were not numbers. Please enter a different file.\n");
}
}
scan.close();
}
public Scanner checkFile(String fileName, Scanner scan) throws IOException
{
File file = new File(fileName);
scan = new Scanner(file);
return scan;
}
public void readFile(Scanner scan)
{
String accountNumber = "";
double accountBalance = -1;
Bank bank = new Bank();
while(scan.hasNext())
{
accountNumber = scan.next();
accountBalance = Double.parseDouble(scan.next());
BankAccount bankAccount = new BankAccount(accountNumber, accountBalance);
bank.addAccount(bankAccount);
}
if (bank.numberOfAccounts() > 0)
{
BankAccount maxBalance = bank.getHighestBalance();
System.out.println(maxBalance.getAccountNumber() + ": " + "$" + maxBalance.getBalance());
}
else
System.out.println("\nThe file had no accounts to compare.");
}
}
Here is the txt file I'm working with:
346583155444415 10000.50
379611594300656 5000.37
378237817391487 7500.15
378188243444731 2500.89
374722872163487 25000.10
374479622218034 15000.59
342947150643707 100000.77
So even though this is my own txt file, what if I was accessing a text file that a character that wasn't a number or had an account number but no balance and vice versa. I would like to know how I can deal with these exceptions.
What I've tried:
I've tried to do scan.nextLine() to move away from the exception but it just introduces another exception.
I've also tried to use a method that uses regex to check if the string is a number. The problem is I'm using a variable that is not a string and I would rather not create more checks.
It seems to me that no more what I do, I can't recover my scanner after an exception has occurred.
before parsing you can test if it is a double with scan.hasNextDouble and parse or read the number only then else you set default value and move next by reading the incorrect value and dont do anything with it
Related
import java.util.Scanner;
import java.io.*;
public class UppercaseFileConverter {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}
//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
System.out.println(line.toUpperCase());
}
}
inputFile.close();
System.out.println("Files read, converted and then closed.");
}
}
When I run my code, my validation that checks whether the file entered exists or not does not run but instead terminates the program. Can I use a try/catch?
You can do three things
1.Remove System.exit()
2.Add null Check before using file object
if (file!=null&&!file.exists()) {}
3.Add try catch block to handle possible exception in your case FileNotFoundException.
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();
i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)
String name = carrot;
double unit_price = 200;
int unit = 10;
This value i want to store in Arraylist, which is present in my main application as follow:
package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
FileReader fin = new FileReader("/home/yati/Desktop/test");
Scanner src = new Scanner(fin);
// Read the ingridient from text file.
while (src.hasNext()) {
if (src.hasNext()) {
i_one.setName(src.next());
System.out.println("Name: " +src.next());
} else
if(src.hasNextDouble()) {
i_one.setUnit_price(src.nextDouble());
System.out.println("Unit Price: " +src.nextDouble());
}
else if (src.hasNextInt()) {
i_one.setUnit(src.nextInt());
System.out.println("Unit: " +src.nextInt());
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
fin.close();
}
}
Her, Ingridient class has following code:
package com.collection;
public class Ingridient {
String name;
Double unit_price;
int unit;
public Ingridient() {
name = null;
unit_price = null;
unit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setUnit_price(Double unit_price) {
this.unit_price = unit_price;
}
public void setUnit(int unit) {
this.unit = unit;
}
}
My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is:
I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?
This should do it:
public static void main(String[] args) throws IOException {
String content = "String name = carrot;\ndouble unit_price = 200;\nint unit = 10;";
try (Scanner sc = new Scanner(content)) {
sc.useDelimiter("(;*\n*.+ .+ = )|;");
List<Incredient> incredients = new ArrayList<>();
while (true) {
Incrediend incredient = new Incredient();
if (sc.hasNext()) {
String name = sc.next();
incredient.setName(name);
System.out.println("Name: " + name);
} else {
break;
}
if (sc.hasNextDouble()) {
double unitPrice = sc.nextDouble();
incredient.setUnit_price(unitPrice);
System.out.println("Unit Price: " + unitPrice);
} else {
break;
}
if (sc.hasNextInt()) {
int unit = sc.nextInt();
incredient.setUnit(unit);
System.out.println("Unit: " + unit);
} else {
break;
}
incredients.add(incredient);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This works because of the delimiter I've used (;*\n*.+ .+ = )|;.
This pice of regex just removes all the parts of the text file that you're not interested in saving.
There are a couple of problems with your approach, for example this:
i_one.setName(src.next());
System.out.println("Name: " +src.next());
Here, you're reading 2 tokens from the scanner because there are 2 calls to next(), if you want to use the same token for multiple things you should create a new variable to store it in (ex: String name = sc.next()).
The default delimiter that the Scanner is using is a single space and because of that, in your code, hasNextDouble() and hasNextInt() will never be true, all the numbers in the text file end with ;.
I'm not sure what you're trying to do here, it is kind of unusual to parse java code from a text file. If you can change the format of the text file, you should chose one that is easier to parse (CSV for example).
src.hasNext() selects every line you've got in your file, so it will never jump into one of the if/else conditions
I would also recommend using json as an input format ;)
while (src.hasNext()) {
if (src.hasNext()) {
it always true and another else {} sections inacessible
The structure of your text file is not very good for parsing the desired values.
If you're able to you should change it to something like
carrot,200,10
thus having all values of your desired ingredient at one line. Splitting this line at "," will give you all the values you need to instantiate your objects.
If you're not able to change the text format (because it's part of the task), you should read whole lines of the text file and interpret triples of them to get your objects. So you also can be sure that all the values you need are there.
your first if condition is wrong to get the output you need...
if (src.hasNext())
this condition will always satisfy as there will be a next object and your following else if conditions never execute. this can be seen in the output always printing the data from the sysout in the first if condition.
i have changed the code to work with startsWith method given by the string class. Hope it helps...
NOTE: before you parse it make sure you remove out those special characters if any. (Semi -colons etc.)
while (src.hasNext()) {
String input = src.next();
if (input.startsWith("name")) {
i_one.setName(input);
System.out.println("Name: " + input);
} else if (input.startsWith("unit_price")) {
i_one.setUnit_price(Double.parseDouble(input));
System.out.println("Unit Price: " + input);
} else if (input.startsWith("unit")) {
i_one.setUnit(Integer.parseInt(input));
System.out.println("Unit : " + input);
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
If the structure of the text file is always the same you can use the contains method of the string class. Example:
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
try(BufferedReader br = new BufferedReader(new FileReader("/home/yati/Desktop/test.txt"))) {
String line ;
while ((line = br.readLine())!=null) {
String [] splited;
if(line.contains("String name")){
splited= line.split(" ");
i_one.setName(splited[splited.length-1].replace(";", ""));
System.out.println(i_one.name);
}
else if(line.contains("double unit_price")){
splited= line.split(" ");
i_one.setUnit_price(Double.parseDouble(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit_price);
}
else if(line.contains("int unit")){
splited= line.split(" ");
i_one.setUnit(Integer.parseInt(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit);
}
}
}
db.add(i_one);
}
}
I am working on an assignment and cannot get this method to produce the correct output to the file. I am supposed to get the mean and write it to the file. Their is the StatsDemo class and the StatsFile class. I am kind of a beginner at Java so I'd like just a little help. My method in the StatsFile class is currently like this:
//returns the calculated arithmetic average
public double calculateMean(String filename) throws FileNotFoundException
{
// declare variables step 5
double accumulator = 0.0;
int counter =0;
String line;
try{
File input = new File(filename);
//create a Scanner object passing it the File object
Scanner keyboard = new Scanner(input);
//for (int i = 0; i < input.length(); i++){
// Read a double from the file.
while(keyboard.hasNextDouble()){
accumulator += keyboard.nextDouble();
// Add to counter
counter++;
}
keyboard.close();
}catch(FileNotFoundException e){
}
return (accumulator/counter);
}
The demo is as such:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class StatsDemo {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
DecimalFormat threeDec = new DecimalFormat("0.000");
Scanner keyboard = new Scanner(System.in);
String filename; // the user input file name
System.out.print("Enter the file name: ");
filename = keyboard.nextLine();
FileStats fileObj = new FileStats(filename);
try{
PrintWriter name = new PrintWriter("Results.txt");
name.println("mean = " + threeDec.format(fileObj.getMean()));
name.println("Standard Deviation = " + threeDec.format(fileObj.getStdDev()));
name.close();
}catch(IOException e){
System.out.println("Error");
}
}
}
The catches and throws still kind of confuse me. My issue is that it currently gives me a question mark instead of the mean when i open the file. Any help will be appreciated.
If an exception that occurs within the try block, control jumps to the catch block. You should think about what should happen in that case. You may be able to correct the problem and continue; you may wish to look at the problem and rethrow and exception, or you may wish just to let your caller handle the problem. In the last case, you don't need a catch at all, you can just need a throws on your method declaration.
Catching an exception and doing nothing is rarely a good idea as the problem is just being ignored. Remember that code flow will carry on after the catch clause unless another exception is thrown, so if the file does not exist, you will still process the return (accumulator/counter) line, which is not what you want.
Looking at your code, your method already throws a FileNotFoundException, so just remove the try and the catch.
I am trying to compile but I seem to be getting an error stating I am missing a ; on a line that has the ;. I have also looked around the code and can't see an error myself. I hope that you can point me in the right direction :)
import java.io.*;
import java.util.*;
public class marks
{
private String asses;
private int mark;
public marks()
{
}
public void createFile() throws Exception
{
File doc;
doc = new File ("marks.txt");
if(!doc.exists()){
doc.createNewFile();
System.out.println("A New File Has been Created");
}
else {
System.out.println ("File Already Exists");
}
}
public void enterMarks()
{
Scanner input new Scaner(doc); <---------- Error ; expected
while (input.hasNext()){
String asses = input.next();
int mark = input.nextInt();
System.out.println( asses +" "+ mark);
}
}
}
You're missing an =:
Scanner input = new Scanner(doc);
Scanner input = new Scanner(doc); "=" is missing and Scanner spells wrong; change visibility doc to global