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();
}
}
Related
I need help with an exercise I am doing. I am currently learning Java. I am doing a factorial exercise, whereby my application prompt a user of a number and then compute the factorial of that number and returned it to be displayed.
This is my GUI class:
public String factorial;
public String fieldnumber;
public String calculateFactorial() {
fieldnumber = this.numberField.getText();
Number number = new Number(Integer.parseInt(fieldnumber));
System.out.print(number.toString());
return number.toString();
}
private void calculateBtnActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println( this.calculateFactorial());
}
This is my Number class:
public class Number {
private int number;
int i,fact=1;
public Number(int number){
this.number = number;
}
public Integer getNumber(){
return this.number;
}
public void setNumber(int number){
this.number = number;
}
private Integer computeFactorial(){
for(i=1; i<=number ;i++){
fact=fact*i;
}
return this.fact;
}
public String toString() {
return Integer.toString(this.computeFactorial());
}
}
When I print my computed factorial the true result is part of the printed garbage value. factorial of 6 is 720, but I am seeing 720518400 the first three numbers are the correct and the garbage not sure where it's coming from.
Please, help
Before the for loop, you must initialize fact=1; because you call the method twice.
private Integer computeFactorial(){
fact = 1;
for(i=1; i<=number ;i++){
fact=fact*i;
}
return this.fact;
}
The program works fine for small numbers but as soon as i take a big number like this it doesn't work
here is my code
public class Main {
public static void main(String[] args) {
long no=600851475143L,i;
int result=0;
for(i=(no/2);i>=2;i--){
if(no%i==0){
if(checkPrime(i)){
System.out.println("Longest Prime Factor is: " + i);
break;
}
}
}
}
private static boolean checkPrime(long i){
for(long j=2L;j<=(int)Math.sqrt(i);j++){
if(i%j==0)
return false;
}
return true;
}
}
to assign long variable value we does not require write L at last on value Remove L.
It will take time to display the answer. Just try with small number(1000000 ) almost 10 to 15 min for above code.
Try this
public class Main {
public static void main(String[] args) {
//long no=600851475143L,i;
System.out.println(largestPrimeFactor(600851475143L));
}
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
}
[1]https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
I have been trying to solve Project Euler Problem #1 using "methods" in Java. It is giving correct multiples. However, sum is not coming right. Here are my codes:
Method Class:
package lessons;
public class method {
int a,b, add;
public void multipleThree()
{
for (a=3; a<1000; a+=3)
{
System.out.println(a);
}
}
public void multipleFive(){
for (b=5; b<1000; b+=5)
{
System.out.println(b);
}
}
public void sum(){
add= a+b;
System.out.println("The sum is "+ add);
}
}
Main Class
package lessons;
public class Lessons {
public static void main(String[] args) {
method problem = new method();
problem.multipleThree();
problem.multipleFive();
problem.sum();
}}
Any helps???
a+b is calculated once - outside your loop. The result will be the sum of the final values of a and b. If you want to sum each element in each loop, you'll need to update add inside the loops:
public class method {
int add = 0;
public void multipleThree() {
for (int a=3; a<1000; a+=3) {
System.out.println(a);
add += a;
}
}
public void multipleFive(){
for (int b=5; b<1000; b+=5) {
System.out.println(b);
add += b;
}
}
public void sum(){
System.out.println("The sum is "+ add);
}
}
The output for multipleThree() and multipleFive() is 999 and 995 accordingly. However a and b are incremented in the for loops one more time to meet the exit condition therefor their sum is 2002 and not 1994.
You can change sum() to this
public void sum(){
add = a + b - 8;
System.out.println("The sum is "+ add);
}
Declare variables separately,
class method {
int i, j, add;
public void multipleThree() {
for (int a = 3; a < 1000; a = a + 3) {
System.out.println(a);
i = a;
}
}
public void multipleFive() {
for (int b = 5; b < 1000; b = b + 5) {
System.out.println(b);
j = b;
}
}
public void sum() {
add = i + j;
System.out.println("The sum is " + add);
}
}
Check below
package lessons;
public class method {
int a,b, add;
public void multipleThree()
{
for (a=3; a<1000; a+=3)
{
System.out.println(a);
}
a=a-3;//added this
}
public void multipleFive(){
for (b=5; b<1000; b+=5)
{
System.out.println(b);
}
b=b-5;//added this
}
public void sum(){
add= a+b;
System.out.println("The sum is "+ add);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner z = new Scanner(System.in);
int N = z.nextInt();
while(N!=0)
{
long number = z.nextInt();
long p = (number-1)/3;
long sum1 = (p*(6+((p-1)*3)))/2;
long q = (number-1)/5;
long sum2 = (q*(10+((q-1)*5)))/2;
long r = (number-1)/15;
long sum3 = (r*(30+((r-1)*15)))/2;
System.out.println(sum1+sum2-sum3);
}
}
}
This is best way to solve the given problem passed all test cases.Happy coding
I would like to write simple program which can offer me feature to print n even numbers starting from some firstNumber. Its number is totalNumber. I don't want to save them, just print them. This is my piece of code:
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
return new myNewIterator();
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
public myNewIterator() {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
totalNumbers--;
return true;
}
return false;
}
#Override
public Integer next() {
return tmp + 2;
}
}
}
And Main:
public class Main {
public static void main(String[] args) {
EvenNumbers en = new EvenNumbers(14, 4);
for (Integer n : en) {
System.out.println(n);
}
}
}
As may you can see, I don't get any output for this program.
Can someone explain me what I doing wrong?
Many thanks!
Why do you have so much code?
public class Main {
public static void main(String[] args) {
int start = 14;
int count = 4;
for (int n = start; n < start + 2 * count; n += 2) {
System.out.println(n);
}
}
}
#fafl answer is a better and concise answer.
To point out why this code was not working:
1. The problem is with your myNewIterator constructor. You were assigning the variable with itself. Also as default value of int is zero and your iteration condition if(totalNumbers > 0) will always fail.
public myNewIterator() {
/** these two lines have to be changed**/
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
/** end **/
this.tmp = firstNumber - 2;
}
You have to take these two values from constructor. Following is the corrected code. I have corrected the constructor name as well.
2. you must not decrement totalNumbers in hasNext() method because say there is a only one next element if I call hasNext() 100 times without calling next() it should still return true i.e. it has next element. So decrement should happen when next() is called.
3. tmp must be updated for every next() call.
These changes also are reflected in following code.
import java.util.Iterator;
public class EvenNumbers implements Iterable<Integer>{
private int firstNumber;
private int totalNumbers;
public EvenNumbers(int firstNumber, int totalNumbers) {
this.firstNumber = firstNumber;
this.totalNumbers = totalNumbers;
}
#Override
public Iterator<Integer> iterator() {
/***** changed *****/
return new myNewIterator(this.firstNumber,this.totalNumbers);
}
private static class myNewIterator implements Iterator<Integer>{
private int firstNumber;
private int totalNumbers;
private int tmp;
/***** changed *****/
public myNewIterator(int firstNo,int totalNo) {
/***** changed *****/
/**** edited these lines *******/
this.firstNumber = firstNo;
this.totalNumbers = totalNo;
/***** ****/
this.tmp = firstNumber - 2;
}
#Override
public boolean hasNext() {
if(totalNumbers > 0){
/***** changed *****/
//totalNumbers--; //commenting this line as repeated calls of this line makes this call unsafe
return true;
}
return false;
}
#Override
public Integer next() {
/***** changed *****/
totalNumbers--;
tmp = tmp + 2
return tmp;
}
}
}
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);
}
}