The output shows zero, variable doesn't store the value - java

The main class:
package tdm;
import java.util.Scanner;
/**
*
* #author abbas
*/
public class TDM {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("** WHAT DO YOU WANT TO FIND? **");
System.out.println("1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame");
System.out.println("2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate");
System.out.println("3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame");
System.out.println("4. Find everything!!");
int choice;
System.out.println();
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1: {
Ex1 ex1 = new Ex1();
ex1.calculateEx1();
break;
}
}
}
}
The Ex1 class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tdm;
import java.util.Scanner;
/**
*
* #author abbas
*/
public class Ex1 {
public void calculateEx1() {
Scanner input = new Scanner(System.in);
int connectionsNum, dataRate, bitMultiplexed;
System.out.print("Enter number of connections: ");
connectionsNum = input.nextInt();
System.out.print("Enter the data rate (Kbps) for each connection: ");
dataRate = input.nextInt();
System.out.print("Enter number of bit(s)");
bitMultiplexed = input.nextInt();
System.out.println("** Your question is **");
System.out.println("The data rate for each one of the " + connectionsNum
+ " connections is " + dataRate + " Kbps. If " + bitMultiplexed
+ " bit at time is multiplexed, what is (A) The duration of each"
+ " input slot, (B) duration of each output slot and (C) duration "
+ "of each frame");
System.out.println("** The answer is **");
int inputSlot = (bitMultiplexed / (dataRate * 1000));
int outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
System.out.println(inputSlot);
System.out.println(outputSlot);
System.out.println(frameDuration);
}
}
The output:
run:
** WHAT DO YOU WANT TO FIND? **
1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame
2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate
3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame
4. Find everything!!
Enter your choice: 1
Enter number of connections: 3
Enter the data rate (Kbps) for each connection: 1
Enter number of bit(s): 1
** Your question is **
The data rate for each one of the 3 connections is 1 Kbps. If 1 bit at time is multiplexed, what is (A) The duration of each input slot, (B) duration of each output slot and (C) duration of each frame
** The answer is **
0
0
0
BUILD SUCCESSFUL (total time: 14 seconds)
As you can see, the three variables inputSlot, outputSlot and frameDuration should store the result of the expression. But as you can see in the output it shows 0. I think this is weird!! This is the first time something like this happen to me.
I suppose it's a small problem but I can't figure out what it's!!

The variables have to be floats instead of Integers. Integers can only store integers as the name sais. Floats can store point nubers like 0.0002. If u divide the int 20 by 11 and store this as a int Java will put 1 as the result. So if your result is 1.9 it is 1.0 as int. That is the Problem here. It looks like this
float inputSlot = (bitMultiplexed / (dataRate * 1000));
float outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
System.out.println(inputSlot);
System.out.println(outputSlot);
System.out.println(frameDuration);
If you have a question ask me :)

Enter the data rate (Kbps) for each connection: 1
Okay, so dataRate = 1.
Enter number of bit(s): 1
And bitMultiplexed = 1.
System.out.println(1 / (1000 * 1)); // 0
Need to cast to a float/double somehow, for example.
System.out.println(1 / (1000.0 * 1)) // 0.001

As you program/answer suggests.
inputSlot = 1 / 10000 = 0;
output = (1/3)*0 = 0;
frameDuration = 3 * 0 = 0;
Since these are int. It will strip the decimal part. Use BigDecimal or double for this purpose

The problem arises due to these 3 fields being initialized as ints. If you make them double your problem will be solved because when you declare them as ints, it will take just the integer part. So for example if you have 0.588 it will take just the 0 which is what is happening as of now.
int inputSlot = (bitMultiplexed / (dataRate * 1000));
int outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
In order to solve this, you need to change the int to double.

Related

Why comes infinite while loop in my code and value not come Zero?

I am writing a code of program that reverse my input, the code that I had written is look like this:
/*
* Author: Mohammed Khalid Alnahdi
*
* This program is reverse the number.
* for example 123 to 321
*
*/
// call utility to take number from the users.
import java.util.Scanner;
class ReverseNumberInput{
public static void main(String[] args){
//we call the tool of take number.
Scanner take = new Scanner(System.in);
int inputNumberUser, printValue = 0;
System.out.print("Please enter the number : ");
inputNumberUser = take.nextInt();
System.out.print("the reverse number is : ");
while(inputNumberUser != 0){
printValue = inputNumberUser % 10;
inputNumberUser = inputNumberUser- printValue;
System.out.printf("%d",printValue);
}
}
}
The answer comes for solve this problem by two why
first solution is replace
inputNumberUser = inputNumberUser- printValue;
by
inputNumberUser = inputNumberUser/10;
and second one is by
while(inputNumberUser != 0){
int digit = inputNumberUser % 10;
printValue = printValue * 10 + digit;
inputNumberUser = inputNumberUser/10;
}
System.out.print(printValue);
My Question why my code in the first not give inputNumberUser zero value while deducting remaining till put the value is zero.
You need to divide the resul of subtraction
inputNumberUser = inputNumberUser- printValue; by 10 after each iteration
For example, you have an input 154
154 - 4 = 150 is your next inputNumberUser
and in the next iteration you have
150 - 0 = 150 is your next inputNumberUser
So your output will be 40000...
If you divide inputNumberUser by 10 after each iteration, you will have
15 - 5 = 10 is your next inputNumberUser
then,
1 - 1 = 0 is your next inputNumberUser

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Nickles in Coin Counter not displaying correct amount

I was just given my first assignment in my Java class, and we were tasked with creating a program that counts nickles and displays the total amount of money. However, whenever I put an odd number of nickles it does not display the corrent amount of money. For example, 1 nickles turns into $.5 instead of $.05. 21 Nickles turns into $1.5 instead of $1.05. I'm asumming this is an easy fix for an easy problem, but I am finding myself stumped. Thanks for the help.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
int nickles5 = nickles * 5;
int dollars = nickles5 / 100;
int change = nickles5 % 100;
System.out.println("You have $" + dollars + "." + change);
}
I'll go out on a limb here, to try to solve your problem. It appears that you will ask the user to enter some number of nickels, and you will output the amount in dollars. Please let me know if this is incorrect in any way.
Now look at the following code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
double nickles5 = nickles * 0.05;
System.out.println("You have $" + nickles5);
}
After we have the number of nickels stored in an int, we multiply it by 0.05, to get the actual value of all the nickels. We store this in a double variable [Note: int multiplied to a double, returns a double; it is called numeric promotion]. Now, to get the total value, you can simply print this double variable. In a case where n=2, nickels5 = 0.1. So, it will print $0.1
If you want this to show up as $0.10, simply replace the nickels5 with String.format( "%.2f", nickels5)
Now your final line will look like:
System.out.println("You have $" + String.format( "%.2f", nickels5));
Let me know if this solved your issue.
You need to format change to use 2 digits, rather than just printing out the raw number. Specifically, if change==5, you want to print out 05.
You can do this with String.format("%02d", change)
You have a random apostrophe at the end, why?
You want to use floats instead of ints, like this:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
System.out.println("$"+ amount);
Output:
Deposit your Nickles.
1
$0.05
Deposit your Nickles.
21
$1.05
EDIT: Code with formatted output:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
String output = String.format("%02f", amount);//f(loat) not d
System.out.println("$"+ output);

Java Currency Converter (How to convert int to Double + Many other issues)

I'm struggling with finding the remainders when converting the currency and then dividing it into dollar amounts. Also, creating a minimum amount of currency to be converted is causing me an issue. I understand alot of my code is a mess but this is my first Java project. Any help would be much appreciated.
/* Currency Conversion
*/
import java.util.Scanner;//to get keyboard input from user
public class Currency {
/**
* Converts from a foreign currency to US Dollars. Takes a
* deduction for the transaction fee. Displays how many of
* each bill and coin denomination the user receives.
*
* #param args no parameters expected
*/
public static void main(String[] args)
{
final double SEK_CONVERSION_RATE = .14;
/*
* You'll need a variable or constant for the transaction fee.
* (3% is fairly typical.) You'll also need a variable or
* constant for the minimum transaction fee.
*/
double transactionFee = .03;
final double MIN_TRANSACTION_FEE = 10.00;
/*
* You're going to need a variable for the amount of that
* currency the user wants to convert.
*/
//Before you can ask the user for input, you need a Scanner so you can read
//that input:
Scanner keyboard = new Scanner(System.in);
/*
* Now you're ready to interact with the user. You'll want
* to greet them and let them know what currency they can convert
* and what the rate of exchange is.
*/
System.out.print("Hello there, welcome to your one and only stop for Swedish Krona conversions. The exchange rate currently sits at .14" );
/*
* You should also let them know about the transaction fee.
*/
System.out.println(" The minimum transaction fee is $10.00 USD.");
/*
* Now you're ready to prompt the user for how much money they
* want to convert.
*/
System.out.println("How many Swedish Krona would you like to convert to US Dollar?");
double userCurrencyInput = keyboard.nextDouble();
/*
* And then use the Scanner to read in that input and initialize your
* variable for currency:
*/
double calculatedCurrInput = (userCurrencyInput*SEK_CONVERSION_RATE);
/* setting up casting to use later in program */
int calculatedCurrInputInt = (int) (calculatedCurrInput);
/*
* You've received an amount in a foreign currency, but you're going
* to need the amount in dollars. Furthermore, you're going to need
* to know the number of 20's, 10's,5's, 1's, quarters, dimes, nickels
* and pennies. And you're going to need to know the transaction fee.
* These should all be stored in variables.
*/
double totalTransaction = (userCurrencyInput*transactionFee + calculatedCurrInput);
int totalTransactionInt = (int) (totalTransaction);
/*Need to define the remainder correct to make change*/
System.out.println("The conversion is " + calculatedCurrInput);
int twentyDollar = 20;
int twentyDollarBills = calculatedCurrInputInt/twentyDollar;
int remainderOfTwenty = calculatedCurrInputInt%twentyDollar;
int tenDollar = 10;
int tenDollarBills = remainderOfTwenty/tenDollar;
int remainderOfTen = remainderOfTwenty%tenDollar;
int fiveDollar = 5;
int fiveDollarBills = remainderOfTen/fiveDollar;
int remainderOfFive = remainderOfTen%fiveDollar;
int oneDollar = 1;
int oneDollarBills = remainderOfFive/oneDollar;
int remainderOfOnes = remainderOfFive%oneDollar;
double remainderOfOnesDBL = (double) remainderOfOnes;
double quarter = .25;
double numberOfQuarters = remainderOfOnesDBL/quarter;
double remainderOfQuarters = remainderOfOnesDBL%quarter;
double dimes = .10;
double numberOfDimes = remainderOfQuarters/dimes;
double remainderOfDimes = remainderOfQuarters%dimes;
double nickels = .05;
double numberOfNickels = remainderOfDimes/nickels;
double remainderOfNickels = remainderOfDimes%nickels;
double pennies = .01;
double numberOfPennies = remainderOfNickels/pennies;
/*
* Now you're ready to calculate the amount in USD.
*/
/*
* Determine what the transaction fee would be, based on the
* percentage.
*/
double totalTransactionFee = (userCurrencyInput*transactionFee);
System.out.println("The transcation fee for your currency exchange would be $" + totalTransactionFee + " US.");
/*
* If the transaction fee is less than the minimum transaction
* fee, you'll need to charge the minimum transaction fee.
* (Hint, the Math class has min and max methods that receive
* two numbers and return either the smaller or larger of those
* two numbers.)
*/
/*
* You'll need to deduct the transaction fee from the total.
*/
/*
* Calculate the number of $20's they'll receive
*/
/*
* How much is left?
*/
/*
* Next do the same for $10's, $5's, etc.
*/
/*
* Finally, let the user know how many dollars their foreign currency
* converted to, what was deducted for the transaction fee, and how
* many of each denomination they are receiving.
*/
System.out.println("The amount of 20's is " +twentyDollarBills);
System.out.println("The amount of 10's is " +tenDollarBills);
System.out.println("The amount of 5's is " +fiveDollarBills);
System.out.println("The amount of 1's is " +oneDollarBills);
System.out.println("The amount of quarters is " +numberOfQuarters);
System.out.println("The amount of dimes is " +numberOfDimes);
System.out.println("The amount of nickels is " +numberOfNickels);
System.out.println("The amount of pennies is " +numberOfPennies);
}//end main
}//end Currency
Firstly, you shouldn't be converting from doubles to ints, as you will lose the amount after the decimal point. e.g.
double num = 1.9;
int number = (int) num;
System.out.println(number);
will print
1
Also, if you do
System.out.println(num % 1);
you get
0.8999999999999999 // not quite 0.9, which is what you were expecting
As #Laf pointed out, use BigDecimal instead.
BigDecimal SEK_CONVERSION_RATE = new BigDecimal(".14");
String userInput = keyboard.nextLine();
// Better precision constructing from a String
BigDecimal userCurrencyInput = new BigDecimal(userInput);
BigDecimal calculatedCurrInput = userCurrencyInput.multiply(SEK_CONVERSTION_RATE);
Hopefully you can work out the rest from there.
Hint: BigDecimal has a method divideAndRemainder() which returns a BigDecimal[], where the first part is the quotient, and the second part is the remainder.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

Beginner Loop GUI

I have to make this GUI that is a CD calculator.
I put in the Initial investment ($): e.g. 2000
the Annual interest rate (%): e.g. (8%)
Ending value ($): e.g. 5000
The program then outputs on a jLabel: The amount of years required are "12" (e.g.)
I need to make a do while loop and a counter.
I did the get text from the 3 text fields then add the initialInvestment with the annual rate % but having trouble with the loop and the counter?
int initialInvestment, endValue, cdvalue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
cdValue = initialInvestment + (initialInvestment * annualRate);
double a = cdValue;
while (a <= endValue){
a = a++;
yearsOutput.setText("The required year needed is: " + a);
}
You're simply adding 1 to a every iteration of the loop. So it'll take a few thousand iterations that way to fullfil the loop requirements.
What you have to do is keep adding the interest every year while keeping count of the years and only update the output after you're done looping.
int initialInvestment, endValue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
// First year interest is counted here.
cdValue = initialInvestment + (initialInvestment * annualRate);
int years = 1;
while (cdValue < endValue){
cdValue = cdValue + (cdValue * annualRate);
years++;
}
yearsOutput.setText("The required year needed is: " + years);

Categories

Resources