I have a problem in my code and i can't find the answer for it.
I only can use if and else and can't use other classes for an example Math.
The code save a value and try to divide in euro coins.
If i enter 4,31 the result is 2x2e + 1x20c + 1x1c and this is ok but if i enter the value 1,20 the result is 1e + 1x10c + 1x5c + 2x2c + 1x1c but the right result is 1e + 1x20c.
I had to add 0.001 in the 1cent coin because if i don't i'll not get a print for it. Adding this is wrong too.
If somebody could help me i would be very grateful.
Regards.
Code:
import java.util.Scanner;
public class Coins {
public static void main(String[] args){
Scanner in= new Scanner(System.in);
int e2 = 0, e1 = 0,c50 = 0, c20=0,c10 = 0,c5 = 0,c2 = 0,c1;
double v;
System.out.println("Quantia em euros: ");
v = in.nextDouble();
e2 = (int)v/2;
v=v-e2*2;
e1=(int)v;
v=(v-e1)*100;
c50=(int)v/50;
v=v-c50*50;
c20=(int)v/20;
v=v-c20*20;
c10=(int)v/10;
v=v-c10*10;
c5=(int)v/5;
v=v-c5*5;
c2=(int)v/2;
v=v-c2*2;
c1=(int)(v+0.001);
if(e2!=0)System.out.print(e2+"X2Eur ");
if(e2!=0&&!(e1==0&&c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(e1!=0)System.out.print(e1+"X1Eur ");
if(e1!=0&&!(c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c50!=0)System.out.print(c50+"X50c ");
if(c50!=0&&!(c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c20!=0)System.out.print(c20+"X20c ");
if(c20!=0&&!(c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c10!=0)System.out.print(c10+"X10c ");
if(c10!=0&&!((c5==0&&c2==0&&c1==0)))System.out.print("+ ");
if(c5!=0)System.out.print(c5+"X5c ");
if(c5!=0&&!(c2==0&&c1==0))System.out.print("+ ");
if(c2!=0)System.out.print(c2+"X2c ");
if(c2!=0&&!(c1==0))System.out.print("+ ");
if(c1!=0)System.out.print(c1+"X1c");
}
}
first of all: if you store a value in a double-variable, always consider that double is a bit imprecise, i'd use cents instead (simply remove the comma and parse to int).
for the implementation itself: optimize the whole thing using arrays.
final int[] coin_values = new int[]{
200 , 100 , 50 , 20 , 10 , 5 , 2 , 1};
final String[] coin_names = new String[]{
"2€" , "1€" , "50ct" , "20ct" , "10ct" , "5ct" , "2ct" , "1ct"};
String input = in.next();
String[] temp = input.split(".");
input = temp[0] + temp[1];
int value = Integer.parseInt(input);
int[] coins = new int[coin_values.length];
for(int i = 0 ; i < coins.length ; i++){
coins[i] = value / coin_values[i];
value %= coin_values[i];
if(coins[i] != 0)
System.out.print(coins[i] + " " + coin_names[i] + " + ");
}
These are rounding errors by Java, they can always occur when using floats. In your case you keep editting the same value so the error gets bigger and bigger.
Use
System.out.println("Quantia em euros: ");
v = 1.20;
int cents = (int)(v*100);
e2 = cents/200;
cents = cents%200;
e1=cents / 100;
cents = cents % 100;
c50=cents/50;
cents = cents%50;
c20=(int)cents/20;
cents = cents %20;
c10=(int)cents/10;
cents = cents%10;
c5=(int)cents/5;
cents = cents % 5;
c2=(int)cents/2;
c1=cents%2;
Because rounding errors don't occur on ints.
In Java always use java.math.BigDecimal for monetary amounts.
You won't get strange rounding behaviour that you can't control.
Related
I'm making a simple while loop when i can make a subtraction between 2 number in java.
The only task of this exercise is this:
Suppose that user insert 2 number by this method (
Scanner keyboard = number.nextInt();
Scanner keyboard2 = number2.nextInt();
Suppose that user insert these 2 number : 8 and 3
I'm not asking for a program which makes 8 - 3 = 5
The program is able to do only substraction or addiction of 1.
so the five is converted in a substraction of -1 for five time.
So instead of 8 - 3, the program calculate 8 -1 -1 -1 -1 -1 = 3
// 8 - 5
Or :
8 -1 = 7
7 - 1 = 6
// ....
4 - 1 = 3
The exercise don't requires complex method, or for loop, only while
As my point of view, i think that you need your answer like your example. Because of that, i made a program for you. In this program if you only enter large number first, you can except if statement, This is my solution.
import java.util.*;
import java.lang.*;
public class Stack2{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
int num1=sc.nextInt();
int num2=sc.nextInt();
if(num1<num2){
System.out.println("Number 1 is less than number 2");
System.exit(1);
}
int x=num1-num2;
System.out.print(num1+" - "+num2+" --> is equal to "+ num1+" " );
while(num1!=x){
System.out.print("-1 ");
num1--;
}
System.out.println("= "+x);
}
}
i'm not sure if you want some like this
int num1 = 8;
int num2 = 5;
int res = num1- num2;
boolean bandera = Boolean.TRUE;
String salida = "";
while(bandera)
{
if(num2 > 0)
{
salida = salida +"-1";
num2--;
}else
{
bandera = Boolean.FALSE;
}
}
System.out.println(num1 + salida + "=" + res);
Your code needs little correction. You haven't declared Scanner object correct and even numbers. Try this code,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.print(num1 + " - " + num2 + " --> Is equal to " + num1);
while(num2 > 0) {
System.out.print(" - 1");
num1 -= 1;
num2--;
}
System.out.println(" = " + num1);
sc.close();
}
Code:
import java.util.Scanner;
public class sdusti00lab1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double AA = 8.25;
double CA = 6.50;
double ACP = 9.00;
double CPC = 6.25;
int numA, numC;
double numSP, numLP;
Scanner keys = new Scanner(System.in);
System.out.print(" enter number of adults ");
numA = keys.nextInt();
System.out.println(" enter number of children ");
numC = keys.nextInt();
System.out.println(" enter number of small popcorn");
numSP = keys.nextDouble();
System.out.println(" enter number of large popcorn");
numLP = keys.nextDouble();
double AAddPrice = (numA*AA);
double CAddPrice = (numC*CA);
double ACPT = ((ACP*.094)*AA);
double CPCT = ((CPC*.094)*CA);
double SPTax = (ACP*.094);
double LPTax = (CPC*.094);
System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
System.out.println("Child admission "+"\t"+numC + "\t$" + CAddPrice);
System.out.println("Adult popcorn "+"\t\t"+ACP + "\t$" + ACPT);
System.out.println("Child popcorn "+"\t\t"+CPC + "\t$" + CPCT);
System.out.println("Tax "+"\t\t\t$"+ (SPTax + LPTax));
System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) );
}
}
I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.
Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.
System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);
There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.
The important aspect to understand here: that process works by you
A) specifying a format that describes how your output should look like
B) you calling a formatter with that format and the numbers to format
Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result
Before this the user inputs an int for numOfTimes. Say it's 5. This will ask the question 5 times. But each time through it will erase the previous value in hrs1. It needs to be a separate variable. So if numOfTimes=5 Then I should get 5 different doubles for "Hour " and 5 different doubles for "Minute ". (assuming the user inputs different times) but they all need to be stored in different variables. How should I do this?
Thank you my question has been answered!
use an array ..
int a[] = new int[5];
for(int i =0;i<5;i++){
a[i] = //your value
}
You just need to put your "calculate average" code outside the for loop. I am not sure exactly how you want to calculate the average. But here are two simple ways.
Method one - keep track of the totals and calculate the basic average.
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
double hrTotal = 0;
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
}
//calculate average
double avdHr1 = hrTotal/numOfTimes;
double timeMin1 = minTotal/numOfTimes;
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
}
Method 2 - Use lists and iterate twice
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
ArrayList<Double> hours = new ArrayList<>();
ArrayList<Double> minutes = new ArrayList<>();
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hours.add(hrs1);
minutes.add(min1);
}
//calculate average
double avgHr1 = 0;
double timeMin1 = 0:
for (int i = 0; i < hours.size(); i++) {
double hour = hours.get(i);
double minute = minutes.get(i);
//ToDo: calculate average so far
}
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
You can use arrays to store the information the user has input. Before the loop, make an array using the new keyword, e.g. double[] hrs=new double[numOfTimes]. In the loop, write to different locations in the array for each input, hrs[i]=in.nextDouble(). You can later read from a position on the array using the syntax 'name[index]', such as 'hrs[2]'. Note that for java and many other languages, arrays start at 0. This means for an array [1,2,3] named arr, arr[1] equals 2 instead of 1. This means it would be best if your for loop was changed from for(int i=1;i<=numofTimes;i++) to 'for(int i=0;i
<SOAPBOX,RANT,HIGHHORSE>
This is more of a code review than a straight answer, but something has been bugging me about newbie questions that I've observed on stackoverrflow.
When developing, I avoid keyboard input like the plague. It is such drudgery, especially with a loop such as in this program. So many newbie questions have user-keyboard input. Why?! It makes development so much more difficult!
I've rewritten your program to add the ability for testing data, completely avoiding the need for user-input during development. When testing is over, just switch the test/live comments around.
I'm sure there's a more elegant way, but this style has worked well for me, and I recommend it.
</SOAPBOX,RANT,HIGHHORSE>
import java.util.*;
import static java.lang.Math.abs;
public class AverageTimeWTestingData {
public static void main(String[] args) {
HourMin24[] ahm = null;
//EXACTLY ONE of the following lines must be commented out
//Test only:
ahm = getTestData();
//Live only:
// ahm = getDataFromUserInput();
double dTotalHours = 0.0;
for (HourMin24 hm : ahm){
System.out.println("Time: " + hm.iHour + ":" + hm.iMin);
dTotalHours += hm.iHour + (hm.iMin / 60);
}
System.out.println("Average time (" + ahm.length + "): " + (dTotalHours / ahm.length));
}
private static final HourMin24[] getDataFromUserInput() {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
ArrayList<HourMin24> al24 = new ArrayList<HourMin24>(numOfTimes);
while(numOfTimes < 0) {
System.out.println("What Time (military time): ");
System.out.print("Hour ");
int iHour = in.nextInt();
System.out.print("Minute ");
int iMin = in.nextInt();
al24.add(new HourMin24(iHour, iMin));
numOfTimes--;
}
return al24.toArray(new HourMin24[al24.size()]);
}
private static final HourMin24[] getTestData() {
System.out.println("TEST MODE ON");
return new HourMin24[] {
new HourMin24(13, 1),
new HourMin24(23, 19),
new HourMin24(0, 59),
new HourMin24(16, 16),
};
}
}
class HourMin24 {
public int iHour;
public int iMin;
public HourMin24(int i_hour, int i_min) {
iHour = i_hour;
iMin = i_min;
}
}
Output:
[C:\java_code\]java AverageTimeWTestingData
TEST MODE ON
Time: 13:1
Time: 23:19
Time: 0:59
Time: 16:16
Average time (4): 13.0