if else java algorithm and psuedocode - java

We would like to assess a service charge for cashing a check. Th service charge depends on the amount of the check. If the check amount is less than 10$, we will charge 1$. If the amount is greater than 10$ but less than 100$, we will charge 10% of the amount. If the amount is greater than 100$, but less than 1,000$, we will charge 5$ plus 5% of the amount. If the value is over 1,000$, we will charge 40$ plus 1% of the amount. Use a multibranch/nested if-else statement to compute for the service charge.
tried writing source code but failed.

I think it will look like this. I put the amount randomly.
int amount = 500;
double pay = 0;
if(amount > 1000){
pay = 40+(amount*0.01);
} else if(amount > 100 && amount < 1000){
pay = 5+(amount*0.05);
} else if(amount > 10 && amount < 100){
pay = amount*0.1;
} else if(amount < 10){
pay = 1;
}
System.out.println(pay+"$")

public double getCharge(int check_amount) {
if (check_amount < 10) {
return 1;
} else if (check_amount < 100) {
return 0.1 * check_amount;
} else if (check_amount < 1000) {
return 5 + 0.05 * check_amount;
} else if (check_amount > 1000) {
return 40 + 0.01 * check_amount;
}
return 0;
}
If we start with the lowest condition, we can neglect to have two conditions in the if statement.
In the main:
public static void main(String[] args) {
System.out.println(getCharge(9)) //when value is less than 10
System.out.println(getCharge(90)) //when value is less than 100
System.out.println(getCharge(900)) //when value is less than 1000
System.out.println(getCharge(5000)) //when value is greater than 1000
}
Output:
1
9
50
90

The question asks for nested if statements, so this code may fair better:
public double getCharge(int check_amount) {
if (check_amount < 1000){
if (check_amount < 100){
if (check_amount <10){
return 1;
}else {
return 0.1*check_amount;
}
} else {
return 5 + 0.05*check_amount;
}
} else {
return 40 + 0.01*check_amount;
}
}
This has the same function as the previous code i posted but as nested if-else statements as per request.

Related

Java method for updating money with cents over 99

I am trying to create a method so that if the user enters a number of cents over 99, the updateMoney method will add dollars accordingly and then place the extra change once the cents goes under 100.
public void updateMoney(int cent) {
int addDollars = 0;
int change = 0;
if (cent > 99) {
for(int i = cent; i > 99; i -= 100)
{
addDollars += 1;
cent -= 100;
}
}
this.dollars = dollars + addDollars;
this.cents = cent;
}
public Money(int dol, int cent) {
if (cent < 0 || dol < 0) {
System.out.println("Invalid amount entered");
} else {
if (cent > 99) {
updateMoney(cent);
}
this.dollars = dol;
this.cents = cent;
}
}
This is the code I am currently working with.
I had originally tried a different method that ended up not working so I tried doing something like this instead but my outputs are still off.
In my driver I ran
Money money = new Money(15, 300); and the output was $15.00 when it should end up being $18.99
You should consider storing your dollars and cents in one long value. The following code takes your dollars and cents, combines them, adds the user's inputted cents correctly, and splits them up in dollars and cents again. But why not just keep them together all the time?
long dollarsWithCents = dollars * 100 + cents;
dollarsWithCents += parsedUserInput;
cents = dollarsWithCents % 100;
dollars = dollarsWithCents / 100;

Java method not calculating [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am writing a method which calculates the commission a company gives its vendor for a given product, however it is not executing. Please help. Here are the guidelines that I have to follow.
This function calculates the commission a company gives its vendor for a given product. The commission is calculated as follows (I can safely assume amount is greater than 0):
If it is an annual license, the rates are:
10% if sale is between $0 and $1,000
15% if sale is between $1,001 and $10,000
20% if sale is above $10,000
If it is a forever license (not an annual one), the rates are:
10% if sale is between $0 and $10,000
15% if sale is between $10,001 and $50,000
20% if sale is above $50,000
I attempted to write the above logic into the following code:
public static int commissionRate(boolean isAnnualLicense, int saleAmount) {
if (isAnnualLicense == true){
if (saleAmount <= 1000){
return commissionRate(true,10);
} else if (saleAmount >= 1001 && saleAmount <= 10000) {
return commissionRate(true,15);
} else if (saleAmount > 10001) {
return commissionRate(true,20);
} else {
if (isAnnualLicense == false) {
if (saleAmount >= 10000) {
return commissionRate(false,10);
} else if (saleAmount >= 100001 && saleAmount <= 50000) {
return commissionRate(false, 15);
} else if (saleAmount >= 50001) {
return commissionRate(false,20);
}
}
}
}
return 0;
}
This is what it is supposed to be executing:
public void testCommission(){
Assert.assertEquals("commision for annual sales, 1,000 should be 10", 10, Assignment3.commissionRate(true,1000));
Assert.assertEquals("commision for annual sales, 1,001 should be 15", 15, Assignment3.commissionRate(true,1001));
Assert.assertEquals("commision for annual sales, 10,000 should be 15", 15, Assignment3.commissionRate(true,10000));
Assert.assertEquals("commision for annual sales, 10,001 should be 20", 20, Assignment3.commissionRate(true,10001));
Assert.assertEquals("commision for OneTime sales, 10,000 should be 10", 10, Assignment3.commissionRate(false,10000));
Assert.assertEquals("commision for OneTime sales, 10,001 should be 15", 15, Assignment3.commissionRate(false,10001));
Assert.assertEquals("commision for OneTime sales, 50,000 should be 15", 15, Assignment3.commissionRate(false,50000));
Assert.assertEquals("commision for OneTime sales, 50,001 should be 20", 20, Assignment3.commissionRate(false,50001));
}
#Grade(points=25)
#Test
Any help is appreciated. Thanks in advance.
Your code will never reach the isAnnualLicense == false part, because it is at the wrong nesting level. It should be like this:
if (isAnnualLicense){
if (saleAmount <= 1000){
return 10;
} else if (saleAmount >= 1001 && saleAmount <= 10000) {
return 15;
} else { // saleAmount > 10001
return 20;
}
} else {
if (saleAmount <= 10000) {
return 10;
} else if (saleAmount >= 100001 && saleAmount <= 50000) {
return 15;
} else { // saleAmount >= 50001
return 20;
}
}
You can further simplify this by assigning commision rate to a variable, and making a single return at the bottom of your method:
int rate;
if (isAnnualLicense){
if (saleAmount <= 1000){
rate = 10;
} else if (saleAmount >= 1001 && saleAmount <= 10000) {
rate = 15;
} else { // saleAmount > 10001
rate = 20;
}
} else {
if (saleAmount <= 10000) {
rate = 10;
} else if (saleAmount >= 100001 && saleAmount <= 50000) {
rate = 15;
} else { // saleAmount >= 50001
rate = 20;
}
}
return rate;

How to correct my prime factorization program?

Here is my program for outputting prime factorization of a given number. I am still just a beginner in java so I know it is not the most efficient code. The problem arises when I input relatively big numbers.
Input: 11 Output: 11
Input: 40 Output: 2 2 2 5
Input: 5427 Output: 3 3 3 3 67
Input: 435843 Output: 3 3 79 613
Input: 23456789 Output: none (there appears to be an infinite loop and the code should return 23456789 since it is a prime number on its own)
What might cause this issue?
import java.util.Scanner;
public class PrimeFactorization {
public static boolean isPrime(long n) {
boolean boo = false;
long counter = 0;
if (n == 1) {
boo = false;
} else if (n == 2) {
boo = true;
} else {
for (long i = 2; i < n; i++) {
if (n % i == 0) {
counter++;
}
}
if (counter == 0) {
boo = true;
}
}
return boo;
}
public static void primeFactorization(long num) {
for (long j = 1; j <= num; j++) {
if (isPrime(j)) {
if (num % j == 0) {
while (num % j == 0) {
System.out.printf(j + " ");
num = num / j;
}
}
}
if (num == 1) {
break;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any number:");
long num = scanner.nextLong();
System.out.print("Prime factorization of your number is: ");
primeFactorization(num);
scanner.close();
}
}
There's no actual error - you're just doing things a very inefficient way. Basically, you're checking every number between 1 and 23456789 for primeness, before dividing.
There's absolutely no point in doing this check. As you work your way up from 1 to 23456789, each time you uncover a factor, you know it has to be prime, because you've already divided out all smaller factors. So if you do all of the following, this will still work correctly, and much more quickly.
Remove the isPrime method completely.
Remove the line if (isPrime(j)) {, and the matching }
Change the loop so that j starts at 2, like for(long j = 2 ; j <= num ; j++) {
Remove if (num == 1) { break; } from the end of the loop. It serves no purpose at all.
No matter how efficient the code, factorizing large numbers takes a while - so long it may feel like the computer has hung. Given your code, even modestly large numbers will take a long time.
The main thing you can do to improve your code's efficiency to to note that for any pair of factors of a number, one of them will be no more than the square root of the number. You can use this fact to limit the loop to reduce the order of you algorithm for O(n) to O(log n).
long sqrt = Math.sqrt(number);
for (long i = 2; i < sqrt; i++) {
...
There are many other things you can do, but this change will have the greatest effect.
If number changes value during the loop (as for example in your second factorizing loop), you'll if course need to recalculate the end value:
for (...)
// if number changes
sqrt = Math.sqrt(number);

Stop function so price isnt less than -500 Java

I've ran into a problem with a method in my program, the task i have been set involves stopping the if statement from running after the balance hits -500, i'v tried if(price < buy && balance > -500) and the current one, while(balance > -500) gives me the result of -594 but the expected result is -495.
although if i take out the {} for the while loop and place a break; right next to the while() it just runs through the junit test which uses a method on the subject class(using observer strategy) to change the price(in this case its setting the price to 0.99 7 times).
From my testing the current solution gives the closest answer, but the part I'm asking for help with is stopping it so it doesn't go over the -500 mark.
'
Thanks in advance and if you want me to add in any more code to help, let me know
#Override
public double getBalance() {
System.out.println("balance " + price);
while(balance > -500)break;
if( price < buy ){
outcome = price * increment;
System.out.println("OUT " + outcome + " ");
}else if(price > sell && portfolio >= 100){
income = price * increment;
}
double total = income - outcome;
balance = balance + total;
}
return balance;
}
edit - ok ive indented it a bit better i hope
I think the problem is that there are no checks if a balance - total will go below -500 before the next iteration begins; simplest way to do this with your current code would be:
double total = income - outcome;
if(balance + total >= -500) {
balance = balance + total;
} else {
break;
}

Creating complex probabilities within Java

I'm trying to create a baseball simulation game within java. I'm utilizing instances of 'pitches' as the the iteration for my system. Within this, I have several different possibilities for the outcome. Hit, miss(strike), foul ball(no effect). I created an array of players from another class that read in specific attributes of my players that I design. The only attributes I'm trying to utilize currently are the power of the hitters and their consistency. I'm using random numbers to generate a certain and depending on where that value lies, determines whether it is a ball or a strike. The 'ball' logic is simple and works effectively; however, I'm only receiving counts of balls for the hitters. I'm stuck on how to implement the logic of probability of a strike(a missed swing) or a hit in regards to the pitch being a strike. The constructor I'm using for the player goes as follows
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
you can ignore the false's and true's and null, just pay attention to the numbers
the first number(10) indicates the speed, not relevant.
The second number(20) indicates the power.
The third indicates the consistency of the hitter.
I apologize if this may be confusing or too elementary, I've only been programming for a little over a month. All help would be greatly appreciated. Currently the only thing printing for me looks a little like
Press 'p' to initiate pitches
p
Ball count is: (0,0)
Ball count is: (0,0)
Ball count is: (0,0)
Ball count is: (0,0)
Ball!
Ball count is: (1,0)
Ball count is: (1,0)
Ball!
Ball count is: (2,0)
Ball count is: (2,0)
Ball count is: (2,0)
Ball!
Ball count is: (3,0)
I don't understand why the program is only recognizing balls and not describing what is printing as nothing, which I assume to be the foul ball(however its not printing my statement)
Please help, and thank you so much!
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("Press 'p' to initiate pitches");
Scanner kb = new Scanner(System.in);
String s = kb.nextLine();
if(s.equalsIgnoreCase("p"))
{
int ball = 0;
int strike = 0;
//10 instances of pitches
for(int i = 0; i < 10; i++)
{
double number = Math.random();
if(number > 0.5)
{
ball++;
if(ball == 4)
{
System.out.println("Ball four, take your base");
break;
}
System.out.print("Ball!");
}
else if(strike() == true)
{
{
if(isMiss() == true)
{
System.out.print(" Strike!");
strike++;
}
else if(isFoul() == true)
{
System.out.println("Foul ball!");
}
}
if(strike == 3)
{
System.out.print(" Player struck out!");
break;
}
}
else
{
if(isHit() == true)
{
System.out.println("The ball was hit!");
System.out.println(isHit());
break;
}
}
System.out.println(" Ball count is: " + "(" + ball + "," + strike + ")");
}
}
}
public static boolean strike()
{
if(isMiss() == true)
{
return true;
}
else if(isFoul() == true)
{
return false;
}
else if(isHit() == true)
{
return true;
}
return false;
}
public static boolean isHit()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return false;
}
if(probability > 6 && probability < 9)
{
return false;
}
if(probability > 9 && probability < 12)
{
return true;
}
return true;
}
System.out.println("The ball was hit!");
}
return false;
}
public static boolean isMiss()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return true;
}
if(probability > 6 && probability < 9)
{
return false;
}
if(probability > 9 && probability < 12)
{
return false;
}
return false;
}
}
return false;
}
public static boolean isFoul()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return false;
}
if(probability > 6 && probability < 9)
{
return true;
}
if(probability > 9 && probability < 12)
{
return false;
}
}
}
return false;
}
I suggest you use your debugger to step through your code as there are many sections which don't make sense to me and I cannot run your code for you using with the Player class (and I cannot make it up as it doesn't make sense ;)
Sections of code which don't make sense are
double probability = Math.random();
so probability is a number between [0, 1)
if(probability > 3 && probability < 6) // always false.
if(probability > 6 && probability < 9) // always false
if(probability > 9 && probability < 12) // always false.
// prints the ball was hit but returns `false` to isHit
System.out.println("The ball was hit!");
}
return false;
For strikes:
if (Math.random() > consistency) { /* strike! */ }
You might want a constant foul ball chance (like if they hit the ball, they have a 10% chance of foul ball:
else if (Math.random() < 0.1) { ... }
And same for power, but maybe multiply it by 0.3 (since home runs are rare):
if (Math.random() < power * 0.3) { ... }
Note that for these to work, your consistency and power variables have to be decimals.
For example, 50% consistency would be 0.5. 20% consistency would be 0.2. Similarly, 1 is the maximum amount of power and 0 is really weak.
0.5 would be in between.

Categories

Resources