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);
}
}
Related
How do I append every user chosen equation in an if, else if statement to a text file. I am not sure where would the best place be to put the append to file because putting it in under every else if statement seems repetitive.
import java.util.Formatter;
import java.util.Scanner;
public class javaCalculator {
public static void main(String[] args){
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
System.out.print("Enter the first number: ");
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
number2 = Double.parseDouble(numbers.nextLine());
if (operator.equals("+")){
String calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
}else if (operator.equals("-")){
String calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
}else if (operator.equals("*")){
String calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
}else if (operator.equals("/")){
String calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
}else{
String calculation = (operator + ":" + " Is not a valid operator!");
}
try {
Formatter file1 = new Formatter("C:\\Users\\27711\\Desktop\\PROGRAMMING\\java\\JavaCalculator");
file1.format(calculation);
}
catch (Exception e){
System.out.println("Error");
}
}
}
There are two problems here:
Attempting to use a variable when it isn't in scope
The way you're writing to a file using Formatter
Making the calculation variable available
All you need to do is declare your calculation variable once, before the if/else statements:
String calculation;
if (operator.equals("+")) {
calculation = number1 + " + " + number2 + " = " + (number1 + number2);
} else if (operator.equals("-")) {
calculation = number1 + " - " + number2 + " = " + (number1 - number2);
} else if (operator.equals("*")) {
String calculation = number1 + " * " + number2 + " = " + (number1 * number2);
} else if (operator.equals("/")) {
calculation = number1 + " / " + number2 + " = " + (number1 / number2);
} else {
calculation = operator + ":" + " Is not a valid operator!";
}
// Code to append to the file
In your current code, you're declaring a different variable in each if/else block, which means no calculation variable is in scope by the time you reach the file appending code.
An alternative approach would be to use a conditional operator. Some folks really don't like multiple uses like this, but I personally think it ends up being very readable:
String calculation =
operator.equals("+") ? number1 + " + " + number2 + " = " + (number1 + number2)
: operator.equals("-") ? number1 + " - " + number2 + " = " + (number1 - number2)
: operator.equals("*") ? number1 + " * " + number2 + " = " + (number1 * number2)
: operator.equals("/") ? number1 + " / " + number2 + " = " + (number1 / number2)
: operator + ":" + " Is not a valid operator!";
Alternatively, you might want to consider a switch statement, maybe in a whole separate method:
private static String calculate(String operator, double number1, double number2) {
switch (operator) {
case "+":
return number1 + " + " + number2 + " = " + (number1 + number2);
case "-":
return number1 + " - " + number2 + " = " + (number1 - number2);
case "*":
return number1 + " * " + number2 + " = " + (number1 * number2);
case "/":
return number1 + " / " + number2 + " = " + (number1 / number2);
default:
return operator + ":" + " Is not a valid operator!"
}
}
... or a switch expression if you're using a recent version of the language.
Writing to the file
The documentation for Formatter starts:
An interpreter for printf-style format strings.
While you can use a Formatter to write to a file, you don't want to interpret printf-style format strings at all... and you're currently not closing the formatter, either.
I'd suggest using the Files class instead. You can just write:
Files.write(Paths.get(filename), Arrays.asList(calculation));
To append, you can pass in StandardOpenOptions.APPEND:
Files.write(
// Where to write...
Paths.get(filename),
// The lines to write...
Arrays.asList(calculation),
// How to open the file...
StandardOpenOption.APPEND);
// 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
I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.
how can I initialize all of my variables more easier?
is there a calculus package?
is there a more efficient solution overall?
import java.util.Scanner;
public class limits {
public static void main(String[] args)
{
String introMessage = " ***Calculus: Limits***" + "\n"
+ "This application uses the method of exhaustion" + "\n"
+ "to test limits. You enter the number that x" + "\n"
+ "approches and this program will give you three" + "\n"
+ "numbers on either side of the limit showing" + "\n"
+ "closer approximations of the limit.";
System.out.println(introMessage);
System.out.println();
String polynomialMessage = "Our function: " + "\n"
+ " lim f(x) = x^2 + x + 1 = L" + "\n"
+ "x -> a";
System.out.println(polynomialMessage);
System.out.println();
System.out.println("As x approaches a, what will our limit L be?");
System.out.println();
can I initialize all of these at once?
// initialize variables
double belowAOne = 0.0;
double belowATwo = 0.0;
double belowAThree = 0.0;
double belowAFour = 0.0;
double aboveAOne = 0.0;
double aboveATwo = 0.0;
double aboveAThree = 0.0;
double aboveAFour = 0.0;
double totalBAOne = 0.0;
double totalBATwo = 0.0;
double totalBAThree = 0.0;
double totalBAFour = 0.0;
double totalAAOne = 0.0;
double totalAATwo = 0.0;
double totalAAThree = 0.0;
double totalAAFour = 0.0;
double L = 0;
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform invoice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
System.out.println("Please enter a whole number between 1 and 10 for a: ");
double a = sc.nextDouble();
if (a > 0 && a <=10 )
{
// calculate L
L = (a*a) + a + 1;
// create values that approaches a
belowAOne = a - .5;
belowATwo = a - .1;
belowAThree = a - .01;
belowAFour = a - .001;
aboveAOne = a + .5;
aboveATwo = a + .1;
aboveAThree = a + .01;
aboveAFour = a + .001;
totalBAOne = (belowAOne * belowAOne) + belowAOne + 1;
totalBATwo = (belowATwo * belowATwo) + belowATwo + 1;
totalBAThree = (belowAThree * belowAThree) + belowAThree + 1;
totalBAFour = (belowAFour * belowAFour) + belowAFour + 1;
totalAAOne = (aboveAOne * aboveAOne) + aboveAOne + 1;
totalAATwo = (aboveATwo * aboveATwo) + aboveATwo + 1;
totalAAThree = (aboveAThree * aboveAThree) + aboveAThree + 1;
totalAAFour = (aboveAFour * aboveAFour) + aboveAFour + 1;
String chart = " x " + "x^2 + x + 1" + "\n"
+ "---------+--------------" + "\n"
+ " " + belowAOne + " : " + totalBAOne + "\n"
+ " " + belowATwo + " : " + totalBATwo + "\n"
+ " " + belowAThree + " : " + totalBAThree + "\n"
+ " " + belowAFour + " : " + totalBAFour + "\n"
+ " " + " a " + " : " + "L" + "\n"
+ " " + aboveAFour + " : " + totalAAFour + "\n"
+ " " + aboveAThree + " : " + totalAAThree + "\n"
+ " " + aboveATwo + " : " + totalAATwo + "\n"
+ " " + aboveAOne + " : " + totalAAOne + "\n";
System.out.println();
System.out.println();
System.out.println();
System.out.println(chart);
System.out.println();
System.out.println("As X approaches " + a + ", our guess "
+ "for L is: " + L);
System.out.println();
// end the program
choice = "n";
}
else
{
System.out.println();
System.out.println("***Invalid Entry***");
System.out.println();
}
}
}
}
Is there a better way to write this program?
or you could use a loop instead like this:
double[] belowA = {a - .5, a - .1, a - .01, a - .001};
double[] totalBA = new double[4];
for(int i = 0; i < 4; ++i) {
totalBA[i] = (belowA[i] * belowA[i]) + belowA[i] + 1;
}
also with a StringBuilder / StringBuffer
and finally you could create a method to handle below/above in the same way without duplicated code
I am trying to validate that there are only three arguments passed. In this program I am looking to pass two integers using command line arguments that look like 23 23 +. But I want an error to display if they enter less than three arguments or more than three arguments. As is right now, it gives the error message when there is more than three arguments but not less than three. Any help would be great please.
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
String arithmetic = args[2];
int length = args.length;
if(length != 3){
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
if (arithmetic.equals("+")) {
int addition = firstNumber + secondNumber;
System.out.println(args[0]+ " " + args[2] + " " + args[1] + " = " + addition);
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
} else if (arithmetic.equals("-")) {
int minus = firstNumber - secondNumber;
System.out.println(args[0]+ " " + args[2] + " " + args[1]+ " = " + minus);
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
} else if (arithmetic.equals("/")) {
int division = firstNumber / secondNumber;
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + division);
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int multiply = firstNumber * secondNumber;
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + multiply);
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
//following prints out to the console what the length of each argument is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
System.out.println("The arguments that was passed would have been " + args[0]+ " " + args[1] + " " + args[2]);
}
}
You have code lines that assume that there are at least 3 arguments before you check how many arguments there are. Move these lines:
// setting up the variable firstNumber and secondNumber
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
String arithmetic = args[2];
below your "!= 3" check. Otherwise if you enter less than 3 command line arguments, you'll get an ArrayIndexOutOfBoundsException on one of those lines before you check how many arguments you have.