I'm sorry, I know this question is probably asked a million different times every day, but I truly can't find the answer I'm looking for. I'm a beginner in Java (I'm in college and learning a bunch of new languages), and my while loop is printing out the same thing every time.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is the loan amount? ");
int amount = scanner.nextInt();
int x = 1;
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
x++;
}
}
}
So the issue is that you never actually change amount after doing your calculations inside the while loop. What I think you want to do, is to set amount = rAmt;, which would produce the following code. This will cause the amount to be decreased by 10% each iteration, and this new value carried forward.
...
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
amount = rAmt;
x++;
}
...
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
I have been provided a piece of code and need to write JUnit Test Case for it. I am stuck regarding the loops and user input.
import java.util.Scanner;
import java.text.*;
public class hotelOccupancy
{
public void calcRate()
{
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat();
int occupied = 0
int totalOccupied = 0
// Get and validate occupancy information for each floor
System.out.println("Enter the number of occupied suites on each of the following floors.\n");
for (int floor = 1; floor <= 10; floor++)
{
System.out.println("\nFloor " + floor+ ": ");
occupied=scan.nextInt();
while (occupied < 0 || occupied > 120)
{
System.out.println("\nThe number of occupied suites must be between 0 and " + 120 );
System.out.println("\n Re-enter the number of occupied suites on floor " + floor + ": ");
occupied = scan.nextInt();
}
// Add occupied suites on this floor to the total
totalOccupied += occupied;
}
// Display results
System.out.println("\n\nThe hotel has a total of " + 120 + " suites.\n");
System.out.println(totalOccupied+ " are currently occupied.\n");
System.out.println("This is an occupancy rate of " + fmt.format(occupancyRate)+ "% \n");
} }
How would I write a JUnit test case that can test for user input and multiple loops? Preferable if I don't have to make changes to the source code.
Thank you.
I am working on a java assignment where you enter the price of an object and the amount a theoretical customer handed you for the item. Then the program returns how much you owe them, and breaks it down into dollars, quarters, dimes, nickles, and pennies that you should give them.
Basically here's what it would look like when it runs
What was the purchase price? (exclude the decimal in calculation if it helps
you)
$98.50
How much money did you pay with? (exclude the decimal)
$100.00
The purchase price was $98.50
You payed $100.0
You received $1.50 in change.
0 one hundred dollar bill(s)
0 fifty dollar bill(s)
0 twenty dollar bill(s)
0 ten dollar bill(s)
0 five dollar bill(s)
1 one dollar bill(s)
2 quarter(s)
0 dime(s)
0 nickel(s)
0 penny/pennies
I understand most of it, but I cant seem to wrap my mind around the breakdown of the change handed back. Here's my code so far, but if someone could show me how to break down the change.
import java.util.*;
public class ChangeTendered {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the purchase price: ");
double price = scan.nextDouble();
System.out.println("Enter the amount payed: ");
double ammountPayed = scan.nextDouble();
double changeDue = ammountPayed - price;
int dollars = (int)changeDue;
System.out.println("Return"+ dollars+ "Dollars");
scan.close();
}
}
On a side note, I just cast the changeDue to an int in order to chop off the decimal and get the dollars due, if that caused any confusion.
Here is an initial approach
int change = (int)(Math.ceil(changeDue*100));
int dollars = Math.round((int)change/100);
change=change%100;
int quarters = Math.round((int)change/25);
change=change%25;
int dimes = Math.round((int)change/10);
change=change%10;
int nickels = Math.round((int)change/5);
change=change%5;
int pennies = Math.round((int)change/1);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
You can add more code to the do it for currency notes as well.
From what I can understand, you need to break the returned money into different bills: 100, 50, 20, 10, 5 ... etc.
I think you can use 'division' to solve the problem in Java. The following pseudo code is how you might solve the problem:
//For example:
double changeDue = 15.5;
double moneyLeft = changeDue;
int oneHundred = moneyLeft / 100;
moneyLeft -= oneHundred * 100;
int fifty = moneyLeft / 50;
moneyLeft -= fifty*50 ;
...
//Just remember to 'floor' the result when divided by a double value:
int quarter = Math.floor( moneyLeft / 0.25);
moneyLeft -= quarter * 0.25 ;
...//Until your minimum requirement.
//Then print out your results.
Hope it helps.
What I did was convert it to a string then do a decimal split to separate the change and dollars.
import java.util.Scanner;
import java.text.DecimalFormat;
public class register
{
public static void main(String[] args)
{
DecimalFormat decimalFormat = new DecimalFormat("0.00");
Scanner kb = new Scanner(System.in);
System.out.print("How much does this item cose? -> ");
double cost = kb.nextDouble();
System.out.print("How many will be purcased? -> ");
double quanity = kb.nextDouble();
double subtotal = (cost * quanity);
double tax = (subtotal * .06);
double total = (subtotal + tax);
System.out.print("How much money has been tendered? -> ");
double tendered = kb.nextDouble();
double change = (tendered - total);
int dollars = (int)change;
int twenties = dollars / 20;
int dollars1 = dollars % 20;
int tens = dollars1 / 10;
int dollars2 = dollars % 10;
int fives = dollars2 / 5;
int dollars3 = dollars % 5;
int ones = dollars3;
String moneyString = decimalFormat.format(change);
String changeString = Double.toString(change);
String[] parts = moneyString.split("\\.");
String part2 = parts[1];
double cents5 = Double.parseDouble(part2);
int cents = (int)cents5;
int quarters = cents / 25;
int cents1 = cents % 25;
int dimes = cents1 / 10;
int cents2 = cents % 10;
int nickels = cents2 / 5;
int cents3 = cents % 5;
int pennies = cents3;
System.out.println("Cost: " + "$" + decimalFormat.format(cost));
System.out.println("Quanity: " + quanity);
System.out.println("Subtotal: " + "$" + decimalFormat.format(subtotal));
System.out.println("Tax: " + "$" + decimalFormat.format(tax));
System.out.println("Total: " + "$" + decimalFormat.format(total));
System.out.println("Tendered: " + "$" + decimalFormat.format(tendered));
System.out.println("Change: " + "$" + moneyString);
System.out.println(twenties + " Twenties");
System.out.println(tens + " Tens");
System.out.println(fives + " Fives");
System.out.println(ones + " Ones");
System.out.println(quarters + " Quarters");
System.out.println(dimes + " Dimes");
System.out.println(nickels + " Nickels");
System.out.println(pennies + " Pennies");
}
}
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class ChangeTenderedWorking {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the purchase price: ");
BigDecimal price = scan.nextBigDecimal();
System.out.println("Enter the amount paid: ");
BigDecimal amountPayed = scan.nextBigDecimal();
Map<Denomination, Integer> changeDue = getDenomination(amountPayed, price);
for(Denomination denomination : changeDue.keySet()) {
System.out.println("Return " + denomination + " bill(s) : "+ changeDue.get(denomination));
}
scan.close();
}
public static Map<Denomination, Integer> getDenomination(BigDecimal amountPayed, BigDecimal price) {
BigDecimal change = amountPayed.subtract(price);
System.out.println("Return change -- "+ change);
Map<Denomination, Integer> changeReturn = new LinkedHashMap<Denomination, Integer>();
for(Denomination denomination : Denomination.values()) {
BigDecimal[] values = change.divideAndRemainder(denomination.value, MathContext.DECIMAL32);
if(!values[0].equals(BigDecimal.valueOf(0.0)) && !values[1].equals(BigDecimal.valueOf(0.0))) {
changeReturn.put(denomination, values[0].intValue());
change = values [1];
}
}
return changeReturn;
}
enum Denomination {
HUNDRED(BigDecimal.valueOf(100)),
FIFTY(BigDecimal.valueOf(50)),
TWENTY(BigDecimal.valueOf(20)),
TEN(BigDecimal.valueOf(10)),
FIVE(BigDecimal.valueOf(5)),
TWO(BigDecimal.valueOf(2)),
ONE(BigDecimal.valueOf(1)),
QUARTER(BigDecimal.valueOf(0.25)),
DIME(BigDecimal.valueOf(0.10)),
NICKEL(BigDecimal.valueOf(0.5)),
PENNY(BigDecimal.valueOf(0.1));
private BigDecimal value;
Denomination(BigDecimal value) {
this.value = value;
}
}
}
For my assignment I am to write a file that uses an input of trials to determine an average for a person winning a prize by opening a soda cap and looking if they won. They have a 1 in 5 chance to win. Once I have the averages for the separate trials, I am to read the trials back and calculate the average. I am having troubles trying to read the doubles from the file. This is my code so far.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class BottleCapPrize
{
public static void main(String[] args) throws IOException
{
double averageBottles = 0.0;
double randNum = 0.0;
int bottleSum = 0;
int numBottles = 1;
int bottle = 0;
int maxRange = 6;
int minRange = 1;
int oneTrial = 0;
int winPrize = 1;
double token = 0;
int totalSumCaps = 0;
Scanner in = new Scanner(System.in);
//Generates bottle number for first test
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
//construct an object called outFile to allow access to output methods of the PrintWriter class
PrintWriter outFile = new PrintWriter(new File("trials.txt"));
//Gets users input for how many trials
System.out.print("Enter the amount of trials: ");
int trials = in.nextInt();
System.out.println();
//Check averages for entered trials
for (int loop = 1; loop <= trials; loop++)
{
//Clears out the loops variables each time through
if(loop != 0)
{
averageBottles = 0;
bottleSum = 0;
oneTrial = 0;
numBottles = 0;
}
for(int x = 1; x <= 20; x++)
{
if(x == 20) //One trial is completed
{
averageBottles = bottleSum / x;
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
}
else if(bottle == winPrize)
{
oneTrial = numBottles;
if(oneTrial == 0)
{
oneTrial = 1;
}
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
}
else if(bottle != winPrize) //not a winner, gets new bottle and increments the number of bottles tested
{
//Replaces the old bottle number for a new bottle
randNum = Math.random();
bottle = ((int)((randNum) * (maxRange - minRange)) + minRange);
oneTrial = numBottles;
numBottles ++;
}
bottleSum += oneTrial; //Adds the sum from each trial
}
outFile.println("Trial " + loop + "." + " " + averageBottles); //Prints the averages to the file
System.out.println("Trial " + loop + "." + " " + averageBottles);
//outFile.println("Trial " + "=" + " " + averageBottles); //Prints the averages to the file
//System.out.println("Trial "+ "=" + " " + " " + averageBottles);
}//end of for loop
outFile.close ( );//close the file when finished
//Read the trial data back in and calculate the average
File fileName = new File("trials.txt");
Scanner inFile = new Scanner(fileName);
//read file and get data
while(inFile.hasNext())
{
token = inFile.nextDouble();
totalSumCaps += token;
}
inFile.close();
double totalAverageCaps = totalSumCaps / trials;
//Print results
System.out.println();
System.out.println("The average number of caps opened in order to win a prize is: " + totalAverageCaps);
}
}
If you're asking how to read in a String and convert it to a double, then all you need to do is use next() from Scanner, which returns a String. Then you can use Double.parseDouble(String s) to convert your String to a double. Or you could use nextDouble() from Scanner.
Not sure if you've learned exception handling yet, but if so, you can use a try-catch block to catch a possible NumberFormatException. Also, if you've learned methods, you should use them, ie you should have as little code as possible in your main. You can use methods to make your code a lot cleaner.
EDIT:
You're getting an InputMismatchException from nextDouble() because the token that you're reading is not a double.