Eliminate zero from result (Java) - 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);
}

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));
}
}

Increase percentage by user input in 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 + "%";
}

Array Length Outcome

My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.

Calculate Average Java

I'm trying to calculate the average of the student scores and as it stands I'm struggling with the calculation part.
In my assignment I was asked to caulculate the avg age of three students and avg. heigth of three students.
Could someone please guide me in the last line of this code, I apologize for the newbie question, really stuck and cannot come up with any solution to why it's not calculating my numbers.
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
int JasperHeigth = (int) 175.5;
int PaulaAge = 25;
int PaulaHeigth = (int) 190.5;
int NicoleAge = 18;
int NicoleHeigth = (int) 165;
//output
Scanner output = new Scanner (System.in);
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
}
}
There are a few things wrong:
int JasperHeigth = (int) 175.5;
int PaulaHeigth = (int) 190.5;
int NicoleHeigth = (int) 165;
Given that these appear to be heights with decimal values, it is likely that you would want to store these as doubles instead of ints. When you declare a value like 175.5 as an integer, it is actually truncated to instead be 175. To store the full value of these numbers, you should instead define them as:
double JasperHeigth = 175.5;
double PaulaHeigth = 190.5;
double NicoleHeigth = 165;
Side note: the reason you had to cast those numbers using (int) was because 175.5 is actually a double literal instead of an int, which was what you declared the variable as before.
Next, this scanner definition line is never used:
Scanner output = new Scanner (System.in);
You would use the Scanner class to get input from the user. For instance, if you wanted the user to enter in some names or numbers. In this case, it doesn't look like you need to request any input from the user so this line can probably be deleted.
And lastly, the problem with displaying your output is in this line:
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
The problem is that by enclosing the numbers within quotation marks, your expected arithmetic will not be evaluated and instead just displayed to the user as character data. If you wanted to evaluate those expressions you could instead pull the math operations out of the quotation marks and concatenate them to the String data using the + operator:
System.out.println("Average\t" + ((20 + 25 + 18) /3) + "\t" + ((175.5 + 190.5 + 165) /3));
However, there are still a few things wrong with this. First, ((20 + 25 + 18) /3) will evaluate as integer division. It will reduce to 63/3 which is 21. However, it would also display 21 if you had 64/3 or 65/3, because integer division truncates the part of the number past the decimal point. To prevent truncation of your desired result, you can cast either one of the numbers in the numerator or denominator to double, or divide by a double literal such as 3.0. So something like this:
System.out.println("Average\t" + ((20 + 25 + 19) /3.0) + "\t" + ((175.5 + 190.5 + 165) /3.0));
Then finally, none of these numbers are actually using the variables you defined earlier, they are completely separate. If you want to actually average the variables you will need to substitute them into the expression like this:
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
Summary
Here is a program with all my suggested edits:
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
double JasperHeigth = 175.5;
int PaulaAge = 25;
double PaulaHeigth = 190.5;
int NicoleAge = 18;
double NicoleHeigth = 165;
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
}
Your last line should probably be something like:
System.out.println("Average age: " + ((JasperAge + PaulaAge + NicoleAge) /3) + ". Average height: " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3) ".");
Mind my calculations, but you get the idea.
Java's an object-oriented language. You might just be starting, but it's never too soon to learn about encapsulation:
public class Student {
private final String name;
private final int age; // bad idea - why?
private final double heightInCm;
public Student(String n, int a, double h) {
this.name = n;
this.age = a;
this.heightInCm = h;
}
public String getName() { return this.name; }
public int getAge() { return this.age; }
public double getHeightInCm() { return this.heightInCm; }
public String toString() {
return String.format("name: '%s' age: %d height: %10.2f (cm)", this.name, this.age, this.heightInCm);
}
}
You just have to make your last print like this:
System.out.println("Average\t " + ((20 + 25 + 18) /3) + "\t " + ((175.5 + 190.5 + 165) /3));
or even better use your variables:
System.out.println("Average\t " + ((JasperAge + PaulaAge + NicoleAge) /3) + "\t " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3));

Methods and arrays

Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/

Categories

Resources