The title is quite confusing, as i am not aware what to title this question. Anyway I have java programming homework that requires a number to be divide into the correct amount of change. I am not getting any message when using the program, i can input the number, then nothing happens.
Thanks
-Jordan
double input; // The input
double l = 0; // Toonies (2.00 dollars)
double t = 0; // loonies (1.00 dollars)
double q = 0; // quarters (0.25 dollars)
double d = 0; // dimes (0.10 dollars)
double n = 0; // nickels (0.05 dollars)
double p = 0; // pennies (0.01 dollars)
System.out.println("Hello, this application will tell you how much"
+ "change you have, based on your input.");
System.out.println("Please enter a real integer");
input = TextIO.getDouble(); // Retrieves the next double entered
while (input > 2) {
t++;
} // Closes of toonie statement
while (input > 1) {
l++;
} // Closes of loonie statement
while (input > 0.25) {
q++;
} // Closes of quarter statement
while (input > 0.1) {
d++;
} // Closes of dime statement
while (input > 0.05) {
n++;
} // Closes of nickel statement
while (input > 0.01) {
p++;
} // Closes of penny statement
System.out.println("You have " // Prints a message saying how many of each coin you have
+ t + "toonies, "
+ l + "loonie(s), "
+ q + "quarter(s), "
+ d + "toonie(s), "
+ n + "toonies(s), "
+ p + "pennies(s), ");
In each of those while loops, you also need to be subtracting the amount from the input. Since you are not, it probably is going into an infinite loop on one of those. For example:
while (input > 2) {
t++;
input -= 2;
}
You are not decrementing the input so you get stuck in an infinite loop in the first while for which the initial condition is true:
You should decrement the input amount in your loops:
while (input > 2) {
t++;
input -=2;
}
The variable 'input' is never reduced, so once one of the while loops is entered, there's no way to exit it, and it will continue until you stop the program by some other means.
I suggest you do you calculations in cents. This way you can use a long. Instead of using a loop, you can just use integer division. This will be faster, shorter and more accurate.
Related
Problem while entering a 3 digit no and getting no result. after entering 123 and when 2 is detected as even, and if user enters 7, it should display 173. but the program is immediately ending. It might be a problem in the last 0 check if-block. but removing it also doesn't help. Thanks in advance!
// in 3 dig, check even dig., replace them with odd and disp.
import java.util.*;
public class p24123 {
public static void main(String[] args) {
int n,h,t,o,m,z=0,z1=0,z2=0,fn;
Scanner ob = new Scanner(System.in);
n=ob.nextInt();
if(n>99&&n<1000){
h= n/100;
o=n%10;
m=n/10;
t=m%10;
if(h%2==0){
z=h;
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit"+h+" with \n");
z=ob.nextInt();
if(z%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z=h;
}
else if(t%2==0) {
System.out.println("Condition enter bokachpda");
z1 = t;
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit" + t + " with \n");
z1 = ob.nextInt();
if (z % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
z1 = t;
}
}
else if(o%2==0){
z2=o;
System.out.println("Enter the odd number you would like to replace the EVEN one's digit"+h+" with \n");
z2=ob.nextInt();
if(z2%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z2=o;
}
}
else if(2==2){
if(h<1||t<1||o<1||z<1||z1<1||z2<1){
System.out.println("Error");
System.exit(0);
}
}
fn=z*100+z1*10+z;
}
}
}
}
Here's your code cleaned up and fixed. I modified as little as possible to keep it at a level a beginner would be comfortable with. Some improvements to be made:
Repeated code like this screams, "Put me in my own function!"
A loop can be used to handle any number of digits, not just three.
Error checking/handling. You should handle bad input. What if the user enters "hello" instead of a number?
Improvements I made:
Your original code never printed a result.
Better formatting. It makes the code easier to read.
Descriptive variable names!
Scanner ob = new Scanner(System.in);
int n = ob.nextInt();
if (n > 99 && n < 1000) {
int hundredsDigit = n / 100;
int tensDigit = n / 10 % 10;
int onesDigit = n % 10;
if (hundredsDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit " + hundredsDigit +" with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
hundredsDigit = replacementDigit;
}
}
if (tensDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit " + tensDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
tensDigit = replacementDigit;
}
}
if (onesDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN one's digit " + onesDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
onesDigit = replacementDigit;
}
}
System.out.println(hundredsDigit * 100 + tensDigit * 10 + onesDigit);
}
I have 2 parts of code, the first one being converting fraction to decimal, and the second one being converting decimal to fraction.
However, I have to combine the two piece of code together and I have no idea.I want it to detect the input as either doubles or fraction and convert it to the other.
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
public class Fractions {
public static void main(String args[]) {
double decimal;
double originalDecimal;
int LIMIT = 12;
int denominators[] = new int[LIMIT + 1];
int numerator, denominator, temp;
int MAX_GOODNESS = 100;
// Get a number to be converted to a fraction
if (args.length == 1) {
decimal = Double.valueOf(args[0]).doubleValue();
} else {
// No number was given, so just use pi
assert args.length == 0;
decimal = Math.PI;
}
originalDecimal = decimal;
// Display the header information
System.out.println("-------------------------------------------------------");
System.out.println("Program by David Matuszek");
System.out.println("Input decimal number to be converted: " + decimal);
System.out.println();
// Compute all the denominators
System.out.println("All computed denominators:");
int i = 0;
while (i < LIMIT + 1) {
denominators[i] = (int)decimal;
System.out.print(denominators[i] + " ");
decimal = 1.0 / (decimal - denominators[i]);
i = i + 1;
}
System.out.println();
System.out.println();
// Compute the i-th approximation
int last = 0;
while (last < LIMIT) {
// Print out the denominators used in this computation
System.out.print("Using these " + (last + 1) + " denominators: ");
for (int j = 0; j <= last; j++) {
System.out.print(denominators[j] + " ");
}
System.out.println();
// Initialize variables used in computation
numerator = 1;
denominator = 1;
temp = 0;
// Do the computation
int current = last;
while (current >= 0) {
denominator = numerator;
numerator = (numerator * denominators[current]) + temp;
temp = denominator;
current = current - 1;
}
last = last + 1;
// Display results
double value = (double)numerator/denominator;
int goodness = denominators[last];
double error = 100 * Math.abs(value - originalDecimal) / originalDecimal;
System.out.print("fraction = " + (int)numerator + "/" +
(int)denominator);
System.out.print(", value = " + value);
System.out.print(", goodness = " + goodness);
System.out.println(", error = " + (int)error + "%");
System.out.println();
// Exit early if we have reached our goodness criterion
if (Math.abs(goodness) > MAX_GOODNESS) break;
}
}
}
If I was doing it all on one prompt, I would make two static methods Fraction.TryParse(), and I would use the built in Double.TryParse(), if decimal.TryParse returns true then you do in fact have a decimal. If it returns false, then you have a Fraction, therefore you have to use the same string you passed into Decimal.TryParse() in Fraction.TryParse(). Of course you will need some sanity checks in your Fraction.TryParse() method. The prompt could look something like this:
Enter Decimal/Fraction: 3.14
Enter Decimal/Fraction: 1 + 1/2
Enter Decimal/Fraction: 1 1/2
Enter Decimal/Fraction: 1 (1/2)
You see, if you want this all on one line you need some way to be able to delimit the characters, like a space, or brackets, or simply a + sign which would be mathematically accurate. If it is all on one line it also simplifies your program a little bit because you don't have multiple prompts for one object. The "1 (1/2)" input is not technically mathematically accurate, but you can kind of see how the data is supposed to be structured, you just can't be mathematically rigid with that prompt.
Here I am using the fraction one and one half, your implementation doesn't have a mixed number implementation, but you could just input 1/2 or something, just regular fractions.
I am creating a program that will calculate two numbers. My issue is 0 will be an illegal input to the program but instead of asking again for two numbers.
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
I've done all the code and it mostly works and there is no visible error.
import java.util.*;
import java.util.Scanner.*;
public class MinilabLoopLogic
{
public static void main(String[ ] args)
{
int num1, num2, divisor, total;
Scanner kb = new Scanner(System.in); //you do it!
System.out.print("Please enter 2 integers (separated by spaces): ");
num1 = kb.nextInt();
num2 = kb.nextInt();
System.out.println("\n\nThis program will generate numbers BETWEEN "+ num1 + " " + num2);
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt();
while (divisor == 0)
{
divisor = kb.nextInt();
}
System.out.println("\n\n----------------------------------------");
//Be able to handle 1st number smaller
// OR 2nd number smalle
//Use the modulus operator to check if a number is divisible
if (num1 < num2)
{
for (total = num1+1; total < num2; total++ )
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
else
{
for (total = num1 - 1; total > num2; total--)
{
if (total % divisor == 0)
{
System.out.println(total);
}
}
}
}
}//end main()
Your problem lies in your while loop looking for the divisor:
System.out.println("\nPlease enter the integer your output should be divisible by: ");
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
divisor = kb.nextInt(); // waits for more divisor input
}
You should output a string to tell the user what the problem is. say:
divisor = kb.nextInt(); // gets your divisor
while (divisor == 0) //if it is illegal, e.g. 0
{
System.out.println("\nYou can't divide by 0. Try again!: ");
divisor = kb.nextInt(); // waits for more divisor input
}
Also, if you want them to have to re-enter the num1 and num2 then scanner input has to happen in that while loop.
You added the following in an edit:
The program continues to run without giving an error, or giving any answer when ZERO is imputed, it's suppose to ask the user to input two different numbers again.
That is because you just loop back to get another value when a zero is entered, without writing any new prompt text.
It also only gets a new divisor number, not "two different numbers". If you looped back to before "Please enter 2 integers", it'd actually end up prompting for all 3 numbers again.
I am trying to approximate pi by iteration. This is only a portion of the code.
I'm trying to put this equation into java: pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 + ... + ((-1)^(i+1)) / (2i - 1) ). The problem I have is the summation of this equation (illustrated in my code). If the user keeps on entering y, the program is supposed to multiply i by 2 and calculate pi until user enters n, then it returns to the main menu.
else if(input == 4)
{
System.out.print("i=1 pi=4.0\tWould you like to continue? (y|n) ");
char y = keyboard.next().charAt(0);
if (y =='y')
{
for (int i=2; i<=1000; i=i*2)
{
int sum = 0;
double pi =4 * (Math.pow(-1, i+1)/(2*i-1));
//Right here, how do I modify it to get a sum across a multitude of i's?
System.out.print("i=" + i + " " + "pi" + "=" + pi + "\tcontinue (y|n)? " );
keyboard.next().charAt(0);
}
}
else
{
}
I think your issue is the difference between the summation equation using i and the programmatic way to loop through a calculation. Something like this will loop through is adding/subtracting the fraction, and then multiply it all by 4 in the end.
boolean plus = true
double sum = 0;
for (double i=1.0; i<=1000; i+=2.0)
{
if (plus) {
sum += 1.0/i;
plus = false;
} else {
sum -= 1.0/i;
plus = true;
}
}
sum *= 4;
This question already has answers here:
How do I get this code to stop input when the sum exceeds 100 and still preform the sum and average?
(2 answers)
Closed 9 years ago.
Yes, I know there are a lot of methods here. It's part of the assignment. In this code everything works as intended except that when numbers are entered that equal sum<=100, the "average" output is wrong. For example: if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25.... the average should be 12.3333. Now, if i enter in 8, 10, 99 the output is count 3 sum 117 and average 39 which is correct. Why is it working for sum>100 but not sum<=100??? I don't get it. What am I missing?
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
if (input!=0){
counter++;
}
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter variables to it
average = (avg(theSum, counter));
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, float num2) {
//Declare and initialize variable for average
//Calculate average
float average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the sentinel value
* of 0 that the user had to enter to exit the input loop in the overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ", Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
}
}
The reason is that you're exiting the while loop in different ways depending on the total sum. If the sum is less than 100, even when you enter the number 0 to "exit", you're still going through the loop an extra time. To be honest, the entire loop needs to be completely restructured; a do...while loop would be much easier to read and debug.
The issue is because of the way you exit the while loop as mentioned by #chrylis. So in case where the sum is <= 100 the counter is 1 larger. But when you print it you get correct result because you update the counter value here:
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) + ", Sum = " + sum + ", Average = " + average);
}
As you see in your example:
"if I put in 8,10,19 and zero to exit the output is count 3 sum 37 average 9.25"
it is because the counter value is 4 (so the avg will be 37/4 = 9.25), but while displaying the result you subtract counter by 1, therefore you get the count as 3.
The do-while loop will solve the issue as the condition would be checked at the last thus the loop will exit in same manner for both <=100 and '>100`.
The do-while loop would be like this:
do{
//here goes your code
}while (input != 0);
Your counter is 1 larger than necessary. Dividing by (counter - 1) would fix it.