Can anyone see what is wrong with my code? I get 0 from return of the calculation.
Created a small calculation on second class and pass the result data to main class, then print.
main class
package javaapplication3;
public class JavaApplication3 {
public static void main(String[] args) {
cal bla = new cal();
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
}
second class
package javaapplication3;
public class cal {
public int total = 11;
public int count = 2508;
public int calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public int getRatio () {
return (calRatio);
}
}
PS: By changing bla.getRatio to bla.caln(); worked. I think I've got other projects mixed up. Thanks for the input guys.
You're doing integer division, which truncates the result to an integer.
You need to cast either operand to double.
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
You never call the caln()-method, so calRatio is 0 forever.
Maybe you meant the following:
bla.caln();
String dCount = String.valueOf(bla.getRatio());
Plus, you try to divide integers. Try this:
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public double getRatio () {
return calRatio;
}
}
You never call the "setter" function caln(), so calRatio was never set. So it returns the 0 for calRatio.
replace
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
by this
public cal () {
calRatio = count / total;
System.out.print(calRatio);
}
Try this:
public static void main(String[] args) {
cal bla = new cal();
bla.caln();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
I get 0 from return of the calculation.
As you should. 11 / 2508 does an integer division which is 0
If you want a non-zero I suggest changing
public double getAverage () {
return (double) total / count;
}
Normally you divide the total by the count to get the average.
It will return 0, always, because you are returning an int type. The result of your division will always be some floating point value, so you need to store it as such, and return it.
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln() {
calRatio = (double)count / (double)total;
System.out.print(calRatio);
}
}
Related
So I'm super new to programming and java, a colleague sent me this challenge to build a simple calculator with all four operation (+, - , / , *) but for only too integers.
Now he's asked me to remove this limit of only two values.
(i.e. 10+20+10+12 = 52 )
how difficult is that, should I be learning this right now ?
public class Calculadora {
private int numero1;
private int numero2;
private int resultado;
public int soma(){
this.setResultado(numero1 + numero2);
return this.resultado;
}
public static int soma(final int numero1, final int numero2){
return numero1 + numero2;
}
public int subtrai(){
this.setResultado(numero1 - numero2);
return this.resultado;
}
public static int subtrai(final int numero1, final int numero2){
return numero1 - numero2;
}
public int multiplica(){
this.setResultado(numero1 * numero2);
return this.resultado;
}
public static int multiplica(final int numero1, final int numero2){
return numero1 * numero2;
}
public int divisao(){
this.setResultado(numero1 / numero2);
return this.resultado;
}
public static int divisao(final int numero1, final int numero2){
return (numero1 / numero2);
}
public int getNumero1() {
return numero1;
}
public void setNumero1(int numero1) {
this.numero1 = numero1;
}
public int getNumero2() {
return numero2;
}
public void setNumero2(int numero2) {
this.numero2 = numero2;
}
public int getResultado() {
return resultado;
}
private void setResultado(int resultado){
this.resultado = resultado;
} ```
Check out varargs:
public Integer sum(Integer... numbers) {
int sum = 0;
for (Integer number : numbers) {
sum += number;
}
return sum;
}
I would look in to the following topics:
infix, postfix, prefix, and the Stack class. That is the essence of evaluating and
processing mathematical expressions of arbitrary length.
If you just use + or - look into ArrayList ArrList... you can add all your operands with ArrList.add( input integer here) an use a for loop to add them: for (into i=0;i<ArrList.length();i++) { result +=ArrList[i];} If you use / and × you would have to sort your operands after the weight of your operators:2+3+4×2 , to use a loop you would have to record it to: (.4×2)+3+2
Note: If, for my first case, you got like 3-4 you would ad them ad Arr[0]=3 and Arr[1]=-3.
I am practicing some Java and one of the applications I am writing asks to output the world population in the next 75 years.
I am using the population growth model. My issue is that my application outputs 'Infinity' in the column where the estimated population should be output.
This is my code:
import java.util.Calendar;
import java.util.regex.Matcher;
public class WorldPopulationGrowth {
public static void main(String[] args) {
double currentWorldPopulation = 7.4e9;
double worldPopulationGrowthRate = 1.13;
double anticipatedWorldPopulation;
int initialYear = Calendar.getInstance().get(Calendar.YEAR);
System.out.println("Year\tAnticipated World Population (in billions)\tPopulation " +
"increase since last year");
System.out.println(String.format("%d\t%.1e\t\t\t\t\t\t\t\t\t\t\tNA", initialYear, currentWorldPopulation) );
for(int i=1; i < 76; i++){
int year = initialYear + i;
double growthExponential = worldPopulationGrowthRate*year*1.0;
anticipatedWorldPopulation = currentWorldPopulation * Math.pow(Math.E, growthExponential);
System.out.println(String.format("%d\t%.1e\t\t\t\t\t\t\t\t\t\t\t", year, anticipatedWorldPopulation));
currentWorldPopulation = anticipatedWorldPopulation;
}
}
}
Let's take a careful look at the first iteration of your code, as if we were debugging it (Make sure you try to do this in the future!)
currentWorldPopulation = 7.4e9
worldPopulationGrowthRate is 1.13
initialYear is 2016
your loop begins, i is 1
year is set to 2017
growthExponential is set to 1.13 * 2017 = 2279.21 (this is the start of your problem)
anticipatedWorldPopulation is set to 7.4e9 * e^2279.21
this is roughly 7.4e9 * 7.05e989... KABOOM
Revisit your calculations, and step through your application (ideally in a debugger) to see your problems.
#Krease found your problem.
I recoded it. Once you fix the issue he found it's fine. I used JDK 8 lambdas and gave you both percentage and exponential growth models. The code prints both for comparison:
import java.util.function.DoubleFunction;
/**
* Simplistic population growth model
* #link https://stackoverflow.com/questions/38805318/getting-infinity-output-instead-of-actual-numbers/38805409?noredirect=1#comment64979614_38805409
*/
public class WorldPopulationGrowth {
public static void main(String[] args) {
double currentWorldPopulation = 7.4e9;
double worldPopulationGrowthRate = 1.13;
int numYears = 76;
int startYear = 1976;
double populationExponential = currentWorldPopulation;
ExponentialGrowthModel modelExpGrowth = new ExponentialGrowthModel(worldPopulationGrowthRate);
double populationPercentage = currentWorldPopulation;
PercentageGrowthModel modelPercentGrowth = new PercentageGrowthModel(worldPopulationGrowthRate);
System.out.println(String.format("%10s %20.3e %20.3e", startYear, currentWorldPopulation, currentWorldPopulation));
for (int i = 1; i < numYears; ++i) {
populationExponential = modelExpGrowth.apply(populationExponential);
populationPercentage = modelPercentGrowth.apply(populationPercentage);
System.out.println(String.format("%10s %20.3e %20.3e", startYear+i, populationExponential, populationPercentage));
}
}
}
class ExponentialGrowthModel implements DoubleFunction<Double> {
private double exponent;
ExponentialGrowthModel(double exponent) {
this.exponent = exponent;
}
private double getExponent() {
return exponent;
}
public void setExponent(double exponent) {
this.exponent = exponent;
}
#Override
public Double apply(double value) {
return value*Math.exp(this.getExponent());
}
}
class PercentageGrowthModel implements DoubleFunction<Double> {
private double percentageIncrease;
PercentageGrowthModel(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
private double getPercentageIncrease() {
return percentageIncrease;
}
public void setPercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
#Override
public Double apply(double value) {
return value*(this.getPercentageIncrease());
}
}
Program is to add and average and list amount of times the "addNumber" method is called.
I can make the Amount work, but nothing else
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("Amount: " + stats.amountOfNumbers());
System.out.println("sum: " + stats.sum());
System.out.println("average: " + stats.average());
}
public class NumberStatistics {
private int amountOfNumbers;
private int addNumber;
private double average;
private int sum;
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;
}
public void addNumber(int number) {
number=addNumber;
addNumber++;
// code here
}
public int amountOfNumbers() {
return addNumber;
// code , here
}
public int sum() {
return this.addNumber++;
}
public double average() {
return sum() / addNumber;
}
My incorrect output:
Amount: 4
sum: 4
average: 0.0
Ok lets start with the constructor.
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;}
Here when you create an object you initialize average and sum to 0 but
this.amountOfNumbers=amountOfNumbers; has no particular effect.
To sum up what i think you wanted to do is something like this:
public NumberStatistics()
{
this.average = 0;//this keyword here is not needed but i used it since you did too
this.sum = 0;
this.amountOfNumbers = 0;
}
Then we go to this block of code here:
public void addNumber(int number) {
number=addNumber;
addNumber++;
}
Ok, this line makes no sense since you are setting the parameter equal to the addNumber variable which is something that does not help you at all, what i think you wanted to do here is the following:
public void addNumber(int number) {
sum += number;//same as sum = sum + number;
amountOfNumbers++;//same as amountOfNumbers = amountOfNumbers +1;
}
Then you need a method that returns the average like this:
public double average() {
return average = sum / amountOfNumbers; //i use the average variable only because you did,
//the most efficient way here is just to return sum / amountOfNumbers
}
Finally, the last two methods that i think you were trying to create are these:
public int amountOfNumbers() {
return amountOfNumbers;
}
public int sum() {
return sum;
}
This is my first post ever so i hope that it helps.
In NumberStatistics, you only need the count and a sum. You add to the sum with addNumber (and increment the count). Something like,
public class NumberStatistics {
private int count = 0;
private int sum = 0;
public void addNumber(int number) {
this.sum += number;
count++;
}
public int getCount() {
return count;
}
public int sum() {
return sum;
}
public double average() {
return sum() / (double) getCount();
}
}
public class homework
{
public static void intPow(int a, int b)
{
Math.pow(a,b);
}
public static void main(String args[])
{
intPow();
}
}
I'm trying to learn how to create a method, but I keep getting 10 ; expected errors. I know this code isn't correct, but I can't seem to find how to create a method correctly. In this case I'm trying to create a method that returns a^b.
You need to pass two int parameters into intPow():
public static void main(String args[])
{
int a = 2;
int b = 5;
intPow(a, b); //32
}
Furthermore, you should probably return an int from intPow() so you can play with it later:
public static int intPow(int a, int b) {
return Math.pow(a, b);
}
Then in main():
public static void main(String args[])
{
int a = 2;
int b = 5;
int power = intPow(a, b); //32
System.out.println(power);
}
pass two int values in intPow();
intPow(5,5);
And anyways the value would not be printed.
You need to use System.out.println() to print it.
Change
intPow();
to
intPow(2,3); // or any number
You declare intPow as a function that takes two parameters. But when you call it from main, you dont pass any. To fix this, change this line in main -
intPow();
to
intPow(1, 2);//or whatever other numbers you want.
public class homework
{
public static int intPow(int a, int b)
{
return Math.pow(a,b);
}
public static void main(String args[])
{
int a = 3;
int b = 4;
int result = intPow(a, b);
System.out.println(result);
}
}
If the goal is to create a method that returns a^b, the method should return a value. You probly need to convert to int though, because Math.pow works with doubles.
public static int intPow(int a, int b) {
return (int) Math.pow(a,b);
}
then call it using two parameters for a and b:
int result = intPow( 2, 3 );
public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55