Is there any way to compress the try/catch block codes? Right now, my code has a try/catch code inside a try/catch code.
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
try {
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
You could do this
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
}
Or with Java 7
try {
...
} catch(ParseException | NoSuchElementException ex) {
...
}
If that's what you meant by compression.
1st of all, a single try block can be followed by a series of catch blocks:
try {
throw IOException("msg");
...
throw InterruptedException("msg");
}
catch (IOException ioe){
...
} catch (InterruptedException ie) {
...
}
This is not the best practice, because you might want to narrow your try/catch blocks to handle smaller content of code regarding the Exceptions
You can only use one try block, and then use catch(Exception ex) to catch all those exceptions. If you want to react to the specific kind of exception, you have to test for it.
You can do it (see below). But you might want to think about the structure of your code, for example, maybe you can restructure so that you don't have to call input.nextLine in each catch block.
if(petType.equals("DOG")) {
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
SimpleDateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
Date vaccineDate = stdDate.parse(input.next());
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
}
catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + input.next() + " is not in mm/dd/yy format!");
input.nextLine();
}
catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
Personally, I don't like nesting try/catch blocks. I wouldn't write it this way; I'd prefer it more like this:
if(petType.equals("DOG")) {
String vaccineDateString;
try {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
DateFormat stdDate = new SimpleDateFormat("MM/dd/yy");
stdDate.setLenient(false);
vaccineDateString = input.next();
Date vaccineDate = stdDate.parse(vaccineDateString);
boolean fixed = input.nextBoolean();
Dog x = new Dog(name,owner,weight,vaccineDate,fixed);
object.addPet(x);
} catch (ParseException ex) {
System.out.println("ERROR - Vaccine date " + vaccineDateString + " is not in MM/dd/yy format!");
input.nextLine();
} catch(NoSuchElementException ex) {
System.out.println("ERROR - Missing fields. Skipping line " + lineNumber + "...");
input.nextLine();
}
}
I would also look askance at your mingling input with all this other stuff. I'd find another way.
Related
if I want to read file from text file and store it in an array,each line goes to correct array
this is the text file
111111,34,24.5,first line
222222,53,22.0,second line
333333,,32.0,third line
44444,22,12.6,
if line is empty through exception saying "title is missing" or something like that.
a code has been made if the array length==4 then display lines in order but if length less than 4 and line is missing throw exception but when I want to put last array[3] gives me error. have a look if you can seethe error that would help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Itry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
while(fileReader.hasNext())
{
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate
// variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println("Sold "+String.format("%-5d", number) +
String.format("%-12s", description )+ " at "+"£"+
String.format("%-5.2f", price));
// Compute total
total += number * price;
} // end of try
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
} //end of if
else if (splitArray[0].length()<1) {
try { splitArray[0] = splitArray[0].trim();
System.out.println(" Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
}
else if (splitArray[1].length()<=1) {
try { splitArray[1] = splitArray[1].trim();
System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[2].length()<=1) {
try { splitArray[2] = splitArray[2].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[3].length()<=1) {
try { splitArray[3] = splitArray[3].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
}//end of while
System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));
}// end of try block
catch (FileNotFoundException e)
{
System.out.println("Error - File does not exist");
}
}
}
You can do it as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File(filename);
fileReader = new Scanner(Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
int count = 1;
while (fileReader.hasNext()) {
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
try {
if (line != null && line.length() > 0) {
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if (splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println(
"Sold " + String.format("%-5d", number) + String.format("%-12s", description)
+ " at " + "£" + String.format("%-5.2f", price));
// Compute total
total += number * price;
} catch (NumberFormatException e) {
System.out.println("Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException(
"Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException("Line#" + count + " is empty");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
count++;
} // end of while
System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
}
A sample run:
This program will try to read data from a text file
Enter the file name: data2.txt
Transactions
================
Sold 34 Apple at £24.50
Line#2 is empty
Sold 53 Mango at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data
Total sales: £1999.00
Content of data2.txt:
111111,34,24.5,Apple
222222,53,22.0,Mango
333333,,32.0,Orange
44444,22,12.6,
I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
I was wondering how you would go about outputting which of the two text boxes is holding the NumberFormatException.
try
{
num1Convert = Integer.parseInt(num1Str);
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
num1.requestFocus();
}
my program compares two numbers, and then returns the value of the numbers added together, but I need to output which of the two textareas are throwing back the exception, but I don't know how to do this. I have wrote within the code where it is necessary to output it.
How about this :
try{
num1Convert = Integer.parseInt(num1Str);
}
catch(NumberFormatException nfe) {
System.out.println("Exception in num1");
}
try{
num2Convert = Integer.parseInt(num2Str);
} catch(NumberFormatException nfe) {
System.out.println("Exception in num2");
}
//EDIT
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
Something like this should do:
String currentString = "";
try
{
currentString = num1Str;
num1Convert = Integer.parseInt(num1Str);
currentString = num2Str;
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
// errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
errorLabel.setText(currentString + " must be an integer");
num1.requestFocus();
}
This is what I have:
try{
String filename = "Names.txt";
FileWriter fw = new FileWriter(filename, true);
BufferedWriter buffer = new BufferedWriter(fw);
buffer.append("NAME: " + name + " AGE: " + age + " ID: " + id + "\n\n");
System.out.println("We have succefully created your account.");
buffer.close();
start();
} catch(IOException e){
System.err.println("ERROR");
}
It always overwrites the first line and does not go to a different one. I've used the append. This is my start method:
// this is the start method
public static void start(){
System.out.println("1) Add Account 2) Exit");
System.out.println("What do you want to do: ");
stuff = input.nextInt();
if (stuff == 1) {
try {
x = new Formatter("Names.txt");
} catch (Exception e) {
System.err.println("ERROR" );
}
newRecord();
} else if(stuff == 2) {
System.exit(0);
} else {
System.err.println("ERROR");
}
}
I guess is this line:
x = new Formatter("Names.txt");
From javadoc
public Formatter(String fileName) throws FileNotFoundException
Parameters:
fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
(I add emphasis to the part that is cleaning your file).
I want a program that saves what you enter into the Input Dialogs (after you click no on the first message dialog) for the next time you run the program. The next time I run the program and I click yes on the option dialog, I'm trying to get the text field to say what the user entered last time an input was made. The code at the bottom just sets the textfield blank for some reason..
public static String fn;
public static String sn;
public static int n;
File f = new File("test.txt");
public void actionPerformed (ActionEvent e){
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
writeToFile();
String fullName = writeToFile();
text.setText("Welcome " + fullName + ".");
}
}
//text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
b.setEnabled(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
pnlButton.setBackground(Color.DARK_GRAY);
}
private String writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
if (n==0){
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
}
if (n==1){
text.setText("Welcome " + fn + ".");
}
//text.setText("Welcome " + savedName + " " + sn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
return savedName;
}
When you open outputStream each time you call writeToFile, it automatically overwrites what was in the file to begin with. This means when you call writeToFile at the beginning of the if statement to handle the Yes option, you erase the previous contents.
To append, use the line outStream = new FileOutputStream(f, true);.
It may be better to consider moving ALL writing into the if block n==1.
An even better solution would be to have two methods; a readFromFile and a writeToFile. Also, consider using parameters that you pass to the methods instead of global variables.