Storing Statistics in Java Calculator Program - java

Creating a basic post fix expression evaluator/calculator program in Java using Eclipse. I want to be able to store some statistics (listed below)
• The highest overall result value
• The lowest overall result value
• The aggregate value (all answers added together)
• The average answer (from all answers of all expressions)
• Total invalid expressions entered
• Total valid expressions entered
Current code: http://pastebin.com/EijjR6jq
Any guidance appreciated, thanks.

An easy solution would be to create an arraylist to store the values (before printing). This arraylist will contain all of the values which you have gotten so far. Sorting it will get you the highest/lowest overall value, summing it up & dividing that sum by the number of elements in the arraylist will get you the aggregate value & average answer.
As for the invalid and valid expressions, counters could be implemented to keep track of those. Increment the respective counter (valid/invalid) depending on the expression entered.
So for example, it will look something like below.
Scanner input = new Scanner(System.in);
int invalidNumberExpressions = 0; //counter for invalids
int validNumberExpressions = 0; //counter for valids
ArrayList<String> values = new ArrayList<String>(); //Arraylist for calculated values
while (true) {
... //Omitted
if ("+".equals(part3)) {
// Note that your calculation ends up with a string, and not a float
values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
}
// Omitted
Could also consider using switch statements & refactoring out the common section of code in both parts into another method so you don't have to repeat the whole section twice. Looks cleaner, too.
Something like the below for the switch statement. I'll leave the refactoring part to you.
switch (part3) {
case "+": values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
break;
... //other cases here
}

Related

Editing a program to use a do while/ while loop from user input in Java

I am fairly new to java, so I don't have much experience with the syntax, I have tried some tutorials online and have watched a few videos on while and do while loops in Java from a user input. However, every edit i try breaks my code. The program below takes an answer from the user, an integer from 1 to 20, and has if statements, that carry out the different scenarios. However, I am trying to make it so that it will keep asking the user for an answer, until they input 0. Here is a part of relevant code:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
System.out.println(
"\nPokemon: " + Bulbasaur.getname() +
"\nType: " + Bulbasaur.getthing_about() +
"\nHealth: " + Bulbasaur.gethp() +
"\nAttack: " + Bulbasaur.getattack() +
"\nDefense: " + Bulbasaur.getdefense() +
"\nSpecial attack: " + Bulbasaur.getspattack() +
"\nSpecial defense: " + Bulbasaur.getspdefense()+
"\nSpeed: " + Bulbasaur.getspeed() +
"\nTotal: " + Bulbasaur.gettotal());
}
.
.
.
There are 19 other if statements similar to this (I know this is inefficient code, but i will be making it efficient if it loops).
How would I add a do while/while loop that loops these statements until 0 is entered?
You need to check answer in the loop condition. You can do the check and assignment to answer in one line
int answer;
while ((answer = Integer.parseInt(reader.nextLine())) != 0) {
// code here
}
Your code would be more efficient if you kept the methods like getName() and all 'non-static', so that they could be called from objects of the classes.
If you've understood how to use int[], double[] etc. type of Arrays, what you can do is create an array of objects of the Pokemon like so:
Object[] pokemon = {new Bulbasaur(), new Ivysaur(), new Venusaur()}; // etc. etc.
int answer = Integer.parseInt(reader.nextLine());
answer = answer - 1; // because arrays start at zero, not one
System.out.println("\nPokemon: " + pokemon[answer].getname() +
"\nType: " + pokemon[answer].getthing_about() +
"\nHealth: " + pokemon[answer].gethp() +
"\nAttack: " + pokemon[answer].getattack() +
"\nDefense: " + pokemon[answer].getdefense() +
"\nSpecial attack: " + pokemon[answer].getspattack() +
"\nSpecial defense: " + pokemon[answer].getspdefense()+
"\nSpeed: " + pokemon[answer].getspeed() +
"\nTotal: " + pokemon[answer].gettotal());
Here's a guide to using Objects if you need it.
By making the methods non-static, you can call them from Objects which belong to an array, and all you have to do to add more Pokemon to the array is add , new WhateverPokemon() to it..
Also, if you want to print the choices to the user, you can do so like this:
for(int i = 0; i < pokemon.length; i++)
{
System.out.println(i+1+". "+ pokemon[i].getName());
}
If you want to add this code, then place it immediately after the Object[] pokemon ....
This is a quite intuitive implementation of what you want:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = -1; // Initialize to a trivial value different from 0
while (answer != 0) { // It will not enter here if initialized to 0!
answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
// Code from the if statement
} // End of if
} // End of while
As #Coffeehouse said, you should take a look at what an array is, and try to use it appropriately. It will shorten your code by quite a lot. Step by step, though :)

java - Random inside while loop causes infinite loop with all same numbers

On the Programming By Doing website I'm stuck on the DoubleDice exercise. It's supposed to run a while loop until you come up with the same value for each dice (doubles - 3 and 3, 4 and 4, etc.)
I've input what I think to be the correct code, but I get this infinite loop that prints out the exact same "randoms" every time through the while loop.
I've pondered this for about a day and decided to give it to SO.
Thanks.
import java.util.Random;
public class diceDoubles {
public static void main(String[] args){
Random dice = new Random();
int roll1 = 1 + dice.nextInt(6);
int roll2 = 1 + dice.nextInt(6);
System.out.println("HERE COMES THE DICE!\n");
while(roll1 != roll2) {
System.out.println("Die 1: " + roll1);
System.out.println("Die 2: " + roll2);
System.out.println("The total is " + (roll1 + roll2) + "\n");
}
}
}
You need to add "variables roll1 and roll12 update code" to while loop, like this:
while(roll1 != roll2) {
roll1 = 1 + dice.nextInt(6);
roll2 = 1 + dice.nextInt(6);
System.out.println("Die 1: " + roll1);
System.out.println("Die 2: " + roll2);
System.out.println("The total is " + (roll1 + roll2) + "\n");
}
Spend some time familiarizing yourself with the control flow of the code, and what each statement does.
<type> <identifier>;
Lines like this DECLARE a variable - i.e., give it a type, and a place in the namespace. Once a variable is declared, references to it will be consistent within its scope, and it cannot be re-assigned. (Mostly. There's some trickiness with member variable and local variables sharing a name, but you don't need to worry about that.)
Note that this doesn't assign a value. Primitive data types (int, boolean, double, etc), will have a default value (0 or false), which references will default to null.
<identifier> = <expression>;
computes the value of an expression, and updates an identifier to hold that value. You can combine these into:
<type> <identifier> = <expression>;
Which will declare a variable and immediately assign it a value.
while(<condition>) { <expressions> }
executes the expressions again and again until the condition becomes false. It only repeats the expressions between the curly braces, though.
In your code, nothing between those braces (i.e., "in the body of the while loop") actually updates those values. You only call the assignment statement outside of the while loop, so nothing ever changes.

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

Validating the sorting functionality using Selenium (Java)

This is my first post for help. Please correct me if you see anything wrong with my post.
I am trying to validate the sorting functionality in a web page with Selenium script (using java). here are the details...
First I go to a User search results page with multiple pages.
It has users with the details: user name, number of miles.
There is a sort filter drop down with values: Values A-Z, Values Z-A, Miles Most, Miles Least, Newest Members, Oldest members . by default the sorting is newest members.
Initially I just want to validate: Values A-Z, Values Z-A, Miles Most and Miles Least Since I could see those values in the search page.
For someone who is looking to solve the same problem. Below code worked for me in validating the sorting of all the string values in a page
//Declare Variables
int eleCount;
List<String> customerNameA = new ArrayList();
List<String> customerNameB = new ArrayList();
// Check for our Customer elements and count them.... replace xxx with your xpath
assertTrue(isElementPresent(By.xpath("xxx")));
elements = driver.findElements(By.xpath("xxx']"));
eleCount = elements.size();
System.out.println("Element count: " + eleCount);
for(int i = 2; i < eleCount; i++){
//Capture the customer name values
//replace xxx with your xpath & replace the value increments for each element in xpath with + i +
customerNameA.add(driver.findElement(By.xpath("xxx")).getText());
System.out.println(driver.findElement(By.xpath("xxx")).getText());
customerNameB.add(driver.findElement(By.xpath("xxx")).getText());
}
Collections.sort(customerNameA);
for (int i=0;i<customerNameA.size();i++) {
System.out.println("Customer Name from input: " + customerNameB.get(i) + "--Customer Name from sorted input: " + customerNameA.get(i));
if (!(customerNameA.get(i).equals(customerNameB.get(i)))) {
System.out.println("Customer Names not sorted: " + i);
break;
}
}
}

Error with BigDecimal calculation regarding User Input

I have this idea for my assignment where I wanted a cash register system to calculate the total for an item when the user enters it's cost price and quantity of said item.
That seemed to work, but then led my main problem - I wanted to let the user type the letter "T" after say, 10 transactions, to find out the total takings for the day.
I tried to use a for loop with the BigDecimal math class within the calculations etc.
I have errors on the words 'valueOf' within my calculations & Eclipse keeps trying to change my values to 'long' & i'm pretty sure that's not right.
My explanation isnt amazing so i'll give you the code i wrote and place comments next to where my errors are ..
try{
Scanner in = new Scanner (System.in);
String t = "T";
int count;
for (count = 1;count<=10;count++){
System.out.println("\n\nValue of Item " + count + " :");
BigDecimal itemPrice = in.nextBigDecimal();
System.out.println("Quantity of item " + count + " :");
BigDecimal itemQuantity = in.nextBigDecimal();
BigDecimal itemTotal = (BigDecimal.valueOf(itemPrice).multiply // error here
(BigDecimal.valueOf(itemQuantity))); // error here
System.out.println("\nTotal for item(s): £" + itemTotal);
count++;
while (t == "T"){
BigDecimal amountOfItems = (BigDecimal.valueOf(itemTotal).divide // error here
(BigDecimal.valueOf(itemQuantity))); // error here
BigDecimal totalTakings = (BigDecimal.valueOf(itemTotal).multiply // error here
(BigDecimal.valueOf(amountOfItems))); // error here
System.out.println("The Total Takings For Today is £" + totalTakings + " " );
}
}
}
}
}
Like I said, the 'red lines' that eclipse uses to show there is an error are only under the words, "valueOf" within my BigDecimal calculations.
Any help would be great because i'm tearing my hair out !!!!
Thanx,
Vinnie.
There's no method BigDecimal.valueOf(BigDecimal). itemPrice and itemQuantity are already BigDecimal values - you don't need any conversion:
BigDecimal itemTotal = itemPrice.multiply(itemQuantity);
EDIT: Okay, so the above solves your immediate problem, but you've also got:
while (t == "T")
{
// Loop that never changes the value of t
}
There are two issues with this:
The loop will always either execute forever, not execute at all, or keep going until an exception is thrown, because the loop condition can never change as you're not changing the value of t. My guess is you want t = System.in.readLine() at some point...
You're comparing two string references here whereas I suspect you want to compare their values, e.g.
while (t.equals("T"))

Categories

Resources