Increase percentage by user input in Java - java

If user input is higher than 100, it increases 5% percent for each unit i.e. 100 or minus return 5%, 101 return 10%, 102 return 15%, so on.
So far I was able to do this:
public class CalculatePercent {
private int numberGiven;
private int finalPerc;
public String numberGiven(int numberGiven) {
this.numberGiven = numberGiven;
if(numberGiven == 100) {
finalPerc=5;
return "The percentage" + " " + "is:" + " " + finalPerc + "%";
}
else if (finalPerc > 100 ) {
}
return finalPerc;
}
}
And this:
import java.util.Scanner;
public class CalculatorApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
CalculatePercent p = new CalculatePercent();
System.out.println("Type the number: ");
String usernumber = p.numberGiven(in.nextInt());
System.out.println(usernumber);
}
}

public class CalculatePercent {
private int numberGiven;
private int finalPerc;
public String numberGiven(int numberGiven) {
this.numberGiven = numberGiven;
if (this.numberGiven <= 100) {
finalPerc = 5;
} else if (this.numberGiven > 100) {
finalPerc = 5 * (this.numberGiven - 99);
/*
Why 99 ?
For examaple :
100 - 99 = 1 * 5 = 5%;
101 - 99 = 2 * 5 = 10%;
102 - 99 = 3 * 5 = 15%
soon
*/
}
return "The percentage" + " " + "is:" + " " + finalPerc + "%";
}
}

I think you want something like
return (numberGiven-99)*5

I think what you are looking for is the following method. I am not sure how you are organizing your classes, but the first problem is that your numberGiven method is not returning a string. The second problem is that there are some "magic numbers in here" i.e. 365. I think what you are looking for is something more like this
public String numberGiven(int numberGiven) {
int finalPerc = 5;
if (numberGiven > 100) {
finalPerc += (numberGiven - 100)*5;
}
return "The percentage" + " " + "is:" + " " + finalPerc + "%";
}

Related

How to convert number to words in java- Counting money in java

So for another project I am supposed to create a program that prompts the user for a monetary value and prints out the least number of bill and coin starting with the highest. So for example, if the user input 47.63, the output would be:
0 hundreds
2 twenties
0 tens, etc.
My problem is that when i put in a certain value (namely 186.41), I should come out with 1 Hundreds
1 Fifties
1 Twenties
1 Tens
1 Fives
1 Ones
1 Quarters
1 Dimes
1 Nickles
1 Pennies.
However, my output in the pennies says "0 pennies"
Here's my code:
public class CountingMoney {
public static BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
public static void main(String [] args) throws IOException{
run();
}
public static void run() throws IOException{
System.out.println("Please enter your monetary value");
String userinput = delta.readLine();
double input = Double.parseDouble(userinput);
int amount = (int) (input / 100);
input -= amount * 100;
System.out.println(amount+ " Hundreds");
amount = (int) (input/50);
input -= amount * 50;
System.out.println(amount + " Fifties");
amount = (int) (input/20);
input -= amount * 20;
System.out.println(amount + " Twenties");
amount = (int) (input/10);
input -= amount*10;
System.out.println(amount + " Tens");
amount = (int) (input/5);
input -= amount *5;
System.out.println(amount + " Fives");
amount = (int) (input/1);
input -= amount *1;
System.out.println(amount + " Ones");
amount = (int) (input/.25);
input -= amount * .25;
System.out.println(amount + " Quarters");
amount = (int) (input/.10);
input -= amount * .10;
System.out.println(amount + " Dimes");
amount = (int) (input/.05);
input -= amount * .05;
System.out.println(amount + " Nickles");
amount = (int) (input/.01);
input -= amount * .01;
System.out.println(amount + " Pennies");
}
}
Below java program demonstrate how to convert a number from zero to one million.
NumberToStringLiteral class :
public class NumberToStringLiteral
{
public static void main(String[] args)
{
NumberToStringLiteral numberToStringLiteral = new NumberToStringLiteral();
int number = 123456;
String stringLiteral = numberToStringLiteral.convertIntegerToStringLiteral(number);
System.out.println(stringLiteral);
}
private String convertIntegerToStringLiteral(int number)
{
if (number < 100)
return from_0_To_100(number);
if ( number >= 100 && number < 1000 )
return from_101_To_999(number);
if ( number >= 1000 && number <= 99999)
return from_1000_and_99999(number);
if (number <= 1000000)
return from_100000_and_above(number);
return Digits.OVER_ONE_MILLION.getStringLiteral();
}
private String from_0_To_100(int number)
{
if (number <= 19 )
return ZeroToNineteen.getStringLiteral(number);
String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 10) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
ZeroToNineteen.getStringLiteral(number % 10) : "";
return Tens.getStringLiteralFromNumber( (number - (number % 10 )) ) + " " + LastDigit;
}
private String from_101_To_999(int number)
{
String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 100) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
ZeroToNineteen.getStringLiteral(number % 100) : "";
if ( (number % 100) > 19)
LastDigit = from_0_To_100(number % 100);
if (LastDigit.isBlank())
return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(0));
return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
}
private String from_1000_and_99999(int number)
{
String LastDigit = (number % 1000 < 20 ) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
if (LastDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.getStringLiteral()))
LastDigit = "";
return from_0_To_100(number / 1000 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
}
private String from_100000_and_above(int number)
{
if (number == 1000000)
return Digits.ONE_MILLION.getStringLiteral();
String lastThreeDigit = (number % 1000 <= 100) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
if (lastThreeDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.toString()))
lastThreeDigit = "";
String number1 = from_101_To_999(number / 1000) + Digits.THOUSAND.getStringLiteral() + lastThreeDigit;
return String.valueOf(number1);
}
private int getNumberOfDigit(int number)
{
int count = 0;
while ( number != 0 )
{
number /= 10;
count++;
}
return count;
}
}
ZeroToNineteen enum :
public enum ZeroToNineteen
{
ZERO(0, "zero"),
ONE(1, "one"),
TWO(2, "two"),
THREE(3, "three"),
FOUR(4, "four"),
FIVE(5, "five"),
SIX(6, "six"),
SEVEN(7, "seven"),
EIGHT(8, "eight"),
NINE(9, "nine"),
TEN(10, "ten"),
ELEVEN(11, "eleven"),
TWELVE(12, "twelve"),
THIRTEEN(13, "thirteen"),
FOURTEEN(14, "fourteen"),
FIFTEEN(15, "fifteen"),
SIXTEEN(16, "sixteen"),
SEVENTEEN(17, "seventeen"),
EIGHTEEN(18, "eighteen"),
NINETEEN(19, "nineteen");
private int number;
private String stringLiteral;
public static Map<Integer, String> stringLiteralMap;
ZeroToNineteen(int number, String stringLiteral)
{
this.number = number;
this.stringLiteral = stringLiteral;
}
public int getNumber()
{
return this.number;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteral(int number)
{
if (stringLiteralMap == null)
addData();
return stringLiteralMap.get(number);
}
private static void addData()
{
stringLiteralMap = new HashMap<>();
for (ZeroToNineteen zeroToNineteen : ZeroToNineteen.values())
{
stringLiteralMap.put(zeroToNineteen.getNumber(), zeroToNineteen.getStringLiteral());
}
}
}
Tens enum :
public enum Tens
{
TEN(10, "ten"),
TWENTY(20, "twenty"),
THIRTY(30, "thirty"),
FORTY(40, "forty"),
FIFTY(50, "fifty"),
SIXTY(60, "sixty"),
SEVENTY(70, "seventy"),
EIGHTY(80, "eighty"),
NINETY(90, "ninety"),
HUNDRED(100, "one hundred");
private int number;
private String stringLiteral;
private static Map<Integer, String> stringLiteralMap;
Tens(int number, String stringLiteral)
{
this.number = number;
this.stringLiteral = stringLiteral;
}
public int getNumber()
{
return this.number;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteralFromNumber(int number)
{
if (stringLiteralMap == null)
addDataToStringLiteralMap();
return stringLiteralMap.get(number);
}
private static void addDataToStringLiteralMap()
{
stringLiteralMap = new HashMap<Integer, String>();
for (Tens tens : Tens.values())
stringLiteralMap.put(tens.getNumber(), tens.getStringLiteral());
}
}
Digits enum :
public enum Digits
{
HUNDRED(3, " hundred and "),
THOUSAND(4, " thousand "),
TEN_THOUSAND(5," thousand "),
ONLY_HUNDRED(0, " hundred" ),
ONE_MILLION(1000000, "one million"),
OVER_ONE_MILLION(1000001, "over one million");
private int digit;
private String stringLiteral;
private static Map<Integer, String> stringLiteralMap;
private Digits(int digit, String stringLiteral)
{
this.digit = digit;
this.stringLiteral = stringLiteral;
}
public int getDigit()
{
return this.digit;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteral(int number)
{
if ( stringLiteralMap == null )
addStringLiteralMap();
return stringLiteralMap.get(number);
}
private static void addStringLiteralMap()
{
stringLiteralMap = new HashMap<Integer, String>();
for ( Digits digits : Digits.values() )
stringLiteralMap.put(digits.getDigit(), digits.getStringLiteral());
}
}
Output :
one hundred and twenty three thousand four hundred and fifty six
Note: I have used all three enum for constant variables, you can also use array.
Hope this will help you, Let me know if you have any doubt in comment section.
When you cast a double to an int with (int), it always rounds down, no matter how close the double value is to the integer just above it. doubles cannot represent values like 186.41 exactly, because they're stored in binary instead of decimal. When you start doing lots of calculations with them, the errors start accumulating.
When I try your program, and show the value that's being rounded:
System.out.println("result of division is " + (input/.01));
amount = (int) (input/.01);
input -= amount * .01;
System.out.println(amount + " Pennies");
it displays
result of division is 0.999999999999658
This is very, very close to 1, so not that much error has been accumulated. But it's not exact. And since casting to (int) rounds down, amount will be 0.
There are two ways to solve this:
1) Use BigDecimal as suggested in the other answer. This is the preferred method of dealing with money. It will represent decimal places exactly.
2) Use Math.round() instead of (int), e.g.
amount = (int) Math.round(input / .01);
Math.round on a double returns a long, so you still need a cast, but it's casting from an integer to another integer so no rounding is involved.
I still recommend using BigDecimal. However, this should help you see that in other situations, where you do need to deal with double, you need to pay attention to what kind of rounding you do. Casting to (int) will often be wrong, depending on what you're trying to do.
The issue you're facing is better explained over here.
To overcome this use BigDecimal. However make sure you set the Scale and RoundingMode. If not you might end up with java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. during your divide operation.
Sample Code on how to modify:
amount = bigDecimal.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).intValue();
bigDecimal = bigDecimal.subtract(new BigDecimal(amount * 100));
System.out.println(amount+ " Hundreds");
You can use below code and it is available in this link
For more reference and discussion you can refer this stack-overflow post
Hope it will solve your need.
package com.test;
import java.text.DecimalFormat;
public class EnglishNumberToWords {
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private EnglishNumberToWords() {}
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20){
soFar = numNames[number % 100];
number /= 100;
}
else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) {
return soFar;
}
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1 :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1 :
tradHundredThousands = "one thousand ";
break;
default :
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
/**
* testing
* #param args
*/
public static void main(String[] args) {
System.out.println("*0* " + EnglishNumberToWords.convert(0));
System.out.println("*1* " + EnglishNumberToWords.convert(1));
System.out.println("*16* " + EnglishNumberToWords.convert(16));
System.out.println("*100* " + EnglishNumberToWords.convert(100));
System.out.println("*118* " + EnglishNumberToWords.convert(118));
System.out.println("*200* " + EnglishNumberToWords.convert(200));
System.out.println("*219* " + EnglishNumberToWords.convert(219));
System.out.println("*800* " + EnglishNumberToWords.convert(800));
System.out.println("*801* " + EnglishNumberToWords.convert(801));
System.out.println("*1316* " + EnglishNumberToWords.convert(1316));
System.out.println("*1316* " + EnglishNumberToWords.convert(1316));
System.out.println("*2000000* " + EnglishNumberToWords.convert(2000000));
System.out.println("*3000200* " + EnglishNumberToWords.convert(3000200));
System.out.println("*700000* " + EnglishNumberToWords.convert(700000));
System.out.println("*9000000* " + EnglishNumberToWords.convert(9000000));
System.out.println("*9001000* " + EnglishNumberToWords.convert(9001000));
System.out.println("*123456789* " + EnglishNumberToWords.convert(123456789));
System.out.println("*2147483647* " + EnglishNumberToWords.convert(2147483647));
System.out.println("*3000000010L* " + EnglishNumberToWords.convert(3000000010L));
}
}

Android for loop is not working like java

This is my Android Java code . I don't understand why it is not working like java code . it is example of prime number . Suppose we want to find prime number between 1 to 5 . So I expect the result 2, 3, 5 . But I only got the result 5 . In my Java code I got the correct result . I mean 2, 3, 5 . Please help me figure out this problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime);
Button btn = (Button)this.findViewById(R.id.click_btn);
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
// Get number from EditText
EditText startnumber = (EditText) findViewById(R.id.first_number);
EditText endnumber = (EditText) findViewById(R.id.second_number);
// get the Strings from the EditTexts
String number1 = startnumber.getText().toString();
String number2 = endnumber.getText().toString();
// Convert Strings to int
int x1number = Integer.parseInt(number1);
int x2number = Integer.parseInt(number2);
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str + String.valueOf(i));
}
}
}
});
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Here is my Java code .
/*
* 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 primenumberstwo;
import java.util.Scanner;
/**
*
* #author vubon
*/
public class PrimeNumberstwo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
System.out.println("Enter your first number: ");
int start = s.nextInt();
System.out.println("Enter your second number: ");
int end = s.nextInt();
System.out.println("List of prime numbers bettween " + start + " and " + end);
for(int i = start; i <= end; i++){
if(isPrime(i)){
System.out.println(String.valueOf(i));
}
}
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
You are overwriting the content of the TextView resp in each iteration that's why you see just le last one.
Try something like this:
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
String result = "";
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
result = result + " " + i;
}
}
if(!("".equalsIgnoreCase(result.trim()))){
resp.setText(str + result);
}
Problem is not in Android SDK. your logic is wrong.
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str += String.valueOf(i));//see change here
}
}
Try with:
str = str + String.valueOf(i);
resp.setText(str);
you have found all prime numbers but override with last one on last loop iterate.
Try that;
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( resp.getText() + String.valueOf(i));
}
}

Calling method on an object, and using same object as parameter for method

I am working on a java program for creating a slot machine. The program works how I want it to but I am not sure if one of my method calls is proper java etiquette. In my main method below, inside my for loop, I call the method rollAndCompare() on the FourTumblers object, machine. This method returns an integer, coin, which represents how much the user won based on the number of tumblers matched. This if-else statement is written in the FourTumblers class. However, I also pass the same machine object as a parameter so that the method can access the tumbler values of the object. Is there a better way to do this? Is this correct?
public static void main(String[] args) {
int coins;
int addtLives;
int bank = 0;
int lives = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter how many games you want to play:");
int num = scan.nextInt();
System.out.println("You have decided to play " + num + " games.\n");
for (int i = 1; i <= num; i++) {
FourTumblers machine = new FourTumblers();
coins = machine.rollAndCompare(machine);
bank += coins;
addtLives = coins/100;
lives += addtLives;
System.out.println("You won " + coins + " coins. That's " + addtLives + " lives.");
System.out.println("You now have a total of " + bank + " coins and " + lives + " lives.\n");
}
scan.close();
}
Here is my rollAndCompare method...
public int rollAndCompare(FourTumblers machine) {
value1 = machine.getValue1();
value2 = machine.getValue2();
value3 = machine.getValue3();
value4 = machine.getValue4();
if ((value1 == value2)&&(value2 == value3)&&(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
System.out.println("Jackpot!");
coins = 600;
return coins;
}
else if (((value1 == value2)&&(value2 == value3))||((value1 == value3)&&(value3 == value4))||((value1 == value2)&&(value2 == value4))||((value2 == value3)&&(value3 == value4))){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 300;
return coins;
}
else if ((value1 == value4)||(value1 == value2)||(value1 == value3)||(value2 == value3)||(value2 == value4)||(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 100;
return coins;
}
else{
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 0;
return coins;
}
}
The times you would want to add an object onto itself in a class is if you are going to compare it with other objects from the same class.
Ex:
public class Sample
{
private String name = "Sample Chocolate";
private int cost = 1;
public boolean compareSample(Sample sample)
{
if (sample.name.equals(name) && cost == sample.cost)
return true;
else
return false;
}
Then from another class:
public class SampleTester
{
public static void main(String[] args)
{
Sample sample1 = new Sample();
Sample sample2 = new Sample();
System.out.println("Are sample one and sample two the same?: " + sample1.compareSample(sample2));
}
}
Otherwise you can simply put nothing inside the parenthesis:
public boolean compareSample()
{
if (name.equals("Sample Chocolate") && cost == 1)
return true;
else
return false;
}
As Ashiquzzman eloquently said: You can call that using this.getValue(), you don't need to pass machine (to be used as machine.getValue()).

Searching an array for term and if statements

I have code that searches for a term in a string and want it to find it then it counts and outputs the total. I am trying to search for another term and output the total of that term.
For example:
for(String[] passenger : passengerList) {
if(passenger[3].equalsIgnoreCase("female")) {
allFemale++;
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1 {
femaleSurvivors++;
}
}
count ++;
}
System.out.println("The number of females who survived: ");
return femaleSurvivors;
}
Now, I want to search for the male and count the times that occurs. Not having any luck.
You would really need to keep track of 4 things, sex (m/f) and status (dead/alive). You can do it all in a single loop. Part of it can be captured in the loop, and part of it could be calculated after the fact.
int survivors = 0;
int femaleSurvivors = 0;
int femaleDeaths = 0;
for(String[] passenger : passengerList) {
boolean isFemale = false;
if(passenger[3].equalsIgnoreCase("female")) {
isFemale = true;
}
if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1) {
survivors ++;
if (isFemale){
femaleSurvivors++;
}
} else {
if (isFemale){
femaleDeaths++;
}
}
}
int totalPassengers = passengerList.size();
int maleSurvivors = survivors - femaleSurvivors;
int deaths = totalPassengers - survivors;
int maleDeaths = deaths - femaleDeaths;
int males = maleSurvivors + maleDeaths;
int females = totalPassengers - males;
System.out.println("Survivors (Total/M/F): " + survivors + "/" + maleSurvivors + "/" + femaleSurvivors);
System.out.println("Deaths (Total/M/F): " + deaths + "/" + maleDeaths + "/" + femaleDeaths);
System.out.println("Totals (All/M/F): " + totalPassengers + "/" + males + "/" + females);

Eliminate zero from result (Java)

Okay so I have built a denomination counter for the Indian currency rupees. Say, if you enter Rs. 3453, it gives this output:
Rs 1000 notes: 3
Rs 500 notes: 0
Rs 100 notes: 4
Rs 50 notes: 1
Rs 20 notes: 0
Rs 10 notes: 0
Rs 5 notes: 0
Rs 2 coins: 1
Rs 1 coin: 1
But I want this output and eliminate all the zeros,
Rs 1000 notes: 3
Rs 100 notes: 4
Rs 50 notes: 1
Rs 2 coins: 1
Rs 1 coin: 1
Here's my code:
import java.io.*;
import javax.swing.JOptionPane;
public class denom {
public static void main(String[] args) throws IOException{
String totalRsString;
int totalRs;
totalRsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalRs = Integer.parseInt(totalRsString);
//Calculations begin here
int thousand, fh, h, f, twenty, t, fi, tw, o;
thousand = totalRs/1000;
int bal = totalRs - (1000*thousand);
fh = bal/500;
bal = bal - (500*fh);
h = bal/100;
bal = bal - (100 * h);
f = bal/50;
bal = bal - (50*f);
twenty = bal/20;
bal = bal - (20*twenty);
t = bal/10;
bal = bal-(10*t);
fi = bal/5;
bal = bal - (5*fi);
tw = bal/2;
bal = bal - (2*tw);
o = bal/1;
bal = bal - (1*o);
//End of calculation
//Print work.
JOptionPane.showMessageDialog(null, "Total Entered is Rs." + totalRsString + "\n" + "\nThousand rupee notes: " + thousand + "\nFive Hundred Notes: " + fh + "\nHundred notes: " + h + "\nFifty notes: " + f + "\nTwenty notes: " + twenty + "\nTen notes: " + t + "\nFive notes: " + fi +
"\nTwo coins: " + tw + "\nOne coins: " + o);
}
}
Rather than building your string as a single expression of the form ... + ... + ..., you can use a StringBuilder (see Javadoc for java.lang.StringBuilder) to assemble it across several statements. For example, something like this:
JOptionPane.showMessageDialog(null, "foo: " + 17 + "\n" + "bar" + 18 + "\n");
can be rewritten like this:
StringBuilder message = new StringBuilder();
message.append("foo: ").append(17).append("\n");
message.append("bar: ").append(18).append("\n");
JOptionPane.showMessageDialog(null, message.toString());
By using this approach, you can wrap any of the individual "append" statements in an if-block that makes sure the value is nonzero before adding it to the string.
As an alternative, consider using an enum to hold the value, kind and count for each form of Currency:
private enum Kind {
Coins, Notes
};
private enum Currency {
// …
Ten(10, Kind.Notes),
Five(5, Kind.Notes),
Two(2, Kind.Coins),
One(1, Kind.Coins);
private int value;
private Kind kind;
private int count;
private Currency(int value, Kind kind) {
this.value = value;
this.kind = kind;
}
};
Then your convert() method can iterate through the Currency instances and return a List<Currency> that includes only non-zero counts.
private static List<Currency> convert(int amount) {
List<Currency> list = new ArrayList<>();
int balance = amount;
for (Currency currency : Currency.values()) {
// update currency.count
// update balance;
if (currency.count != 0) {
list.add(currency);
}
}
return list;
}
Finally, you can loop though the List<Currency> to print the result:
List<Currency> list = convert(3453);
for (Currency currency : list) {
System.out.println("Rs "
+ currency.value + " "
+ currency.kind + ": "
+ currency.count);
}
You need to build the output string step-by-step. If the corresponding number of coins or notes for that specific input is equal to zero, you should skip that element in the final string.
Something like:
string output = "Total Entered is Rs." + totalRsString + "\n";
if(thousand == 0){
output += "\nThousand rupee notes: " + thousand;
}
/* Here you will do the same for the rest of notes and coins */
JOptionsPane.showMessageDialog(null, output);
Well, this is a lazy solution. But it's up to you to implement it in a more elegant way.
try reducing the number of variables you are creating. See the ones which can be reused.
StringBuilder sb = new StringBuilder();
int totalRs = 5500;
int bal = totalRs;
int numNotes =0;
if ((numNotes =bal/1000) > 0){
sb.append("Rs 1000 notes: " + numNotes + "\n");
bal = bal - (1000 * numNotes);
}
if ((numNotes =bal/500) > 0) {
sb.append("Rs 500 notes: " + numNotes + "\n");
bal = bal - (500 * numNotes);
}

Categories

Resources