I want to be able to have my catch request users to input the name of the file until the file name is valid, would anyone be able to give me a suggestion on how to arrange my code to do this?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Requierment2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
System.out.println ("Press K for keyboard or F to read expressions from a file");
String user_input=keyboard.nextLine();
String [] ui = user_input.split(" ");
if (ui[0].equals( "k") | ui[0].equals("K")) {
while (true){
System.out.println("Please Enter a Post-Fix Expression (eg: 5 2 *)");
String postfix=keyboard.nextLine();
String [] elements =postfix.split(" ");
if (postfix.equals("")){
System.out.println("Application Closed");
keyboard.close();
System.exit(0);
}
if (elements.length >=3){
try{
float num1, num2;
num1 = Float.parseFloat(elements[0]);
num2 = Float.parseFloat(elements[1]);
if(elements[2].equals("+")){
System.out.println("Total: "+(num1 + num2));
}
else if(elements[2].equals("*")){
System.out.println("Total: "+(num1 * num2));
}
else if(elements[2].equals("/")){
System.out.println("Total: "+(num1 / num2));
}
else if(elements[2].equals("-")){
System.out.println("Total: "+(num1 - num2));
}
else{
System.out.println("Error Invalid Expression: "+ postfix);
}
}
catch(NumberFormatException e){
System.out.println("Error Invalid Expresion: "+postfix);
}
}
else if (elements.length <3) {
System.out.println("Error Invalid Expression: "+ postfix);
}
}
}
else if (ui[0].equals( "f") | ui[0].equals("F"))
{
try{
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
Scanner s = new Scanner(new File(filename));
System.out.println("Processing "+ filename);
System.out.println( );
String line= s.nextLine();
String array []= line.split(" ");
if (array.length >=3){
try{
float array1, array2, total1, total2, total3, total4, array3 , array5;
array1 = Float.parseFloat(array[0]);
array2 = Float.parseFloat(array[1]);
total1 = array1 + array2;
total2 = array1 * array2;
total3 = array1 / array2;
total4 = array1 - array2;
if(array[2].equals("+")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total1);
System.out.println( );
}
else if(array[2].equals("*")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total2);
System.out.println( );
}
else if(array[2].equals("/")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total3);
System.out.println( );
}
else if(array[2].equals("-")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2]+ " " + array2 + " = " + total4);
System.out.println( );
}
else{
System.out.println(" Error Invalid Expression: "+ line);
System.out.println( );
}
}
catch(NumberFormatException e){
System.out.println(" Error Invalid Expresion: "+ line);
System.out.println( );
}
}
else if (array.length <3) {
System.out.println(" Error Invalid Expression: "+ line);
System.out.println( );
}
while ( s.hasNext() ) {
String nl= s.nextLine();
String ar []= nl.split(" ");
if (ar.length >=3){
try{
float ar1, ar2, total1, total2, total3, total4;
ar1 = Float.parseFloat(ar[0]);
ar2 = Float.parseFloat(ar[1]);
total1 = ar1 + ar2;
total2 = ar1 * ar2;
total3 = ar1 / ar2;
total4 = ar1 - ar2;
if(ar[2].equals("+")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total1);
System.out.println( );
}
else if(ar[2].equals("*")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total2);
System.out.println( );
}
else if(ar[2].equals("/")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total3);
System.out.println( );
}
else if(ar[2].equals("-")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2]+ " " + ar2 + " = " + total4);
System.out.println( );
}
else{
System.out.println(" Error Invalid Expression: "+ nl);
System.out.println( );
}
}
catch(NumberFormatException e){
System.out.println(" Error Invalid Expresion: "+ nl);
System.out.println( );
}
}
else if (array.length <3) {
System.out.println(" Error Invalid Expression: "+ nl);
System.out.println( );
}
}
}
catch (FileNotFoundException e){
System.out.println("Error: That file does not exist, please re-enter: ");
filename= keyboard.nextLine();
Scanner s ;
}
}
else{
System.out.println("Neither K or F have been entered");
System.out.println("System Terminated");
keyboard.close();
}
}
}
Print a more comprehensive example of the type of file name you require with the rules.
Use 'visitor' pattern to implement exception rules.
I would suggest not relying on exceptions at all, and instead look at the isFile() or exists() and isDirectory() methods of the File() class. So create a simple loop that keeps looping until a valid filename is entered, or while isFile() is false.
Example 1:
import java.io.File;
import java.util.Scanner;
public class Requirement2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
while (true) {
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
File file = new File(filename);
if (!file.isFile()) {
System.out.println("File does not exist. Try again.");
}
else {
System.out.println("File exists. Proceeding.");
break;
}
}
keyboard.close();
}
}
Example 2:
import java.io.File;
import java.util.Scanner;
public class Requirement2v2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
File file = new File(filename);
while (!file.isFile()) {
System.out.println("File does not exist. Try again.");
filename= keyboard.nextLine();
file = new File(filename);
}
System.out.println("File exists. Proceeding.");
keyboard.close();
}
}
Related
Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.
// I'm searching for an Int in a text file, displaying that Int on console, creating a text file to print that Int. I get this instead of an Int:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=666][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]1920: ,
public static void findName(Scanner input, String name) throws FileNotFoundException {
boolean find = false;
while (find == false && input.hasNext()) {
String search = input.next();
if (search.startsWith(name) && search.endsWith(name)) {
PrintStream output = new PrintStream(new File(name + ".txt"));
output.println(name + ",");
System.out.println("1920: " + input.nextInt());
output.println("1920: " + input + ","); // need help here. HOW DO I GET THIS TO PRINT THE SAME INT, NOT GO TO THE SECOND INT?
System.out.println("1930: " + input.nextInt());
output.println("1930: " + input + ",");
System.out.println("1940: " + input.nextInt());
output.println("1940: " + input + ",");
System.out.println("1950: " + input.nextInt());
output.println("1950: " + input + ",");
System.out.println("1960: " + input.nextInt());
output.println("1960: " + input + ",");
System.out.println("1970: " + input.nextInt());
output.println("1970: " + input + ",");
System.out.println("1980: " + input.nextInt());
output.println("1980: " + input + ",");
System.out.println("1990: " + input.nextInt());
output.println("1990: " + input + ",");
System.out.println("2000: " + input.nextInt());
output.println("2000: " + input);
find = true;
}
}
if (find == false) {
System.out.println("name not found.");
you're printing the input object instead of the int into the file.
try this:
int next = input.nextInt()
System.out.println("1920: " + next );
output.println("1920: " + next + ",");
...
Hope this helps
The logic I'm trying to construct is when the user collects four total affiliates, the console will print that they've reached four but they can still go on if they choose to.
If they decide to stop at four, they should type "quit". The problem rises at the second while loop with the if else statements. I get the error "aff cannot be resolved".
import java.util.Scanner;
public class Seption {
public static void main(String[] args) {
System.out.println("Welcome back!");
Scanner userName = new Scanner(System.in);
System.out.println("Username: ");
String username = userName.next();
Scanner passWord = new Scanner(System.in);
System.out.println("Password: ");
String password = passWord.next();
int affCount = 0;
while (affCount <= 4) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4) {
System.out.println("Congratulations! You've accumulated 4 affiliates!"
+ " any new affiliates added to this branch will be extra earnings"
+ " You can also make a new branch and start over"
+ " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false) {
Scanner newAff = new Scanner(System.in);
System.out.println("enter new affiliate");
String aff = newAff.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit")) {
System.out.println("This branch is now over");
break;
}
}
}
}
You should just create an instance of the Scanner from System.in once and use that same instance anywhere that you need to get an input from the user:
public static void main(String[] args){
System.out.println("Welcome back!");
Scanner scanner = new Scanner(System.in);
System.out.println("Username: "); String
username = scanner.next();
System.out.println("Password: ");
String password = scanner.next();
int affCount = 0;
String aff = "";
while (affCount <= 4) {
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
if (affCount == 4)
{
System.out.println("Congratulations! You've accumulated 4 affiliates!" + " any new affiliates added to this branch will be extra earnings" + " You can also make a new branch and start over" + " To quit this branch, Type 'quit'");
continue;
}
}
while (affCount > 4) {
if (aff.equals("quit") == false)
{
System.out.println("enter new affiliate");
aff = scanner.nextLine();
System.out.println("Alright, " + aff + " is now your new affiliate!");
affCount = affCount + 1;
System.out.println("You now have " + affCount + " affiliates");
}
else if (aff.equals("quit"))
{
System.out.println("This branch is now over");
break; }
}
}
Having difficulty storing the following statistics to be printed when the program terminates. I have been able to store the total number of valid and invalid expressions however I am having difficulty with the following:
The highest overall result value.
The lowest overall result value.
The aggregate of all result values, i.e. all results added together.
The average result value
Any guidance for any of the above would be much appreciated.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
int lowestval = 0;
int highestval;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
}
}
} else if ("K".equals(choice)) // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.exit(0);
}
}
}
}
}
I have changed something wrong on logic and syntax,but I have not debuged it ,you may have a try.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
float lowestval = 0;
float highestval =0 ;
float total=0;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else{
invalidExcepressions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}
} else if ("K".equals(choice)){ // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
}else{
invalidExceotions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}else if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.out.println("Total :"+total);
System.out.println("Average :"+total/validExceptions);
System.exit(0);
}
}
I am having some problem reading the value ba,fr,lit and mid. May I know how should I resolve it. I tried declaring them as global variables but it was to no avail. Kindly help thanks, below is the code, the error occurs on this line ( fileout.println(m + " , " + l + " , " + s + " , " + u + " , " + ba + " , " + " , " + fr + " , " + lit + " , " + mid );)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String m = model.getText();
String l = line.getText();
String s = shift.getText();
String u = unitno.getText();
String ba;
String fr;
String lit;
String mid;
try{
Double b = Double.parseDouble(back.getText());
if(b<350 || b>625){
back.setForeground(Color.BLUE);
back.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 350 to 625. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
ba = back.getText();
}
}
else{
ba = back.getText();
back.setForeground(Color.BLACK);
back.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
back.setForeground(Color.BLUE);
back.setBackground(Color.YELLOW);
}
try{
Double f = Double.parseDouble(front.getText());
if(f<350 || f>625){
front.setForeground(Color.BLUE);
front.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 350 to 625. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
fr = front.getText();
}
}
else{
fr = front.getText();
front.setForeground(Color.BLACK);
front.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
front.setForeground(Color.BLUE);
front.setBackground(Color.YELLOW);
}
try{
Double li = Double.parseDouble(little.getText());
if(li<0.8 || li>3.4){
little.setForeground(Color.BLUE);
little.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 0.8 to 3.4. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
lit = little.getText();
}
}
else{
lit = little.getText();
little.setForeground(Color.BLACK);
little.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
little.setForeground(Color.BLUE);
little.setBackground(Color.YELLOW);
}
try{
Double mi = Double.parseDouble(middle.getText());
if(mi<0.8 || mi>3.4){
middle.setForeground(Color.BLUE);
middle.setBackground(Color.YELLOW);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "The value that you have entered is not within the range of 0.8 to 3.4. Press yes to save anyway and cancel to edit.", "Error", dialogButton);
if(dialogResult ==0){
mid = middle.getText();
}
}
else{
mid = middle.getText();
middle.setForeground(Color.BLACK);
middle.setBackground(Color.WHITE);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please ensure that it is in integer.");
middle.setForeground(Color.BLUE);
middle.setBackground(Color.YELLOW);
}
BufferedWriter output = null;
FileInputStream fs = null;
FileWriter fout = null;
try {
// TODO add your handling code here:
File myFile = new File("C:/Users/kai/Desktop/capforce.txt");
if(!myFile.exists()) {
myFile.createNewFile();
}
fs = new FileInputStream("C:/Users/kai/Desktop/capforce.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
output = new BufferedWriter(new FileWriter(myFile,true));
PrintWriter fileout = new PrintWriter(output,true);
if (br.readLine() == null) {
fileout.println("Model" + " " + "Date" + " " + " " + "Line" + " " + "Shift" + " " + "Unit Number" + " "+ "Capped Force - Capped Z1 (Back)" + " " + "Capped Force - Capped Z1 (front)" + " " +"Wiper to pen interference Z(Little man)" + " " + "Wiper to pen interference Z(Middle man)" );
}
for(int i = 1; i<100; ++i){
String line = br.readLine();
if(line==null){
fileout.println(m + " , " + l + " , " + s + " , " + u + " , " + ba + " , " + " , " + fr + " , " + lit + " , " + mid );
break;
}
}
} catch (IOException ex) {
Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.dispose();
}
Initialize all variables:
String ba = null;
String fr = null;
String lit = null;
String mid = null;