Hello everyone I am a newbie with the java programming language and have been learning the use of methods, below is a simple method i wrote for adding two numbers but when I run the code, it doe not display any output, please what I am doing wrongly? the code should sum numbers from 2 to 4 in this case
//testing Java methods
public class Methods {
public static void main(String [] args) {
int addition = add (2,4);
System.out.println(addition);
}
//the method for addition
public static int add(int a, int b){
int sum = 0;
for (int i = a; a <= b ; i++)
sum += i;
return sum;
}
}
for (int i = a; a <= b ; i++)
It should be
for (int i = a; i <= b ; i++)
It was actually running into infinite loop.
try this program (change from a <= b to i <= b)
public static void main(String[] args) {
int addition = add(2, 4);
System.out.println(addition);
}
// the method for addition
public static int add(int a, int b) {
int sum = 0;
for (int i = a ; i <= b ; i++) {
sum += i;
}
return sum;
}
output
9
your for loop should be
for (int i = a; i <= b ; i++)
//testing Java methods
public class Methods {
public static void main(String[] args) {
int addition = add(2,4);
System.out.println(addition);
}
//the method for addition
public int add(int a, int b){ // Place this method in the class.
int sum = 0;
for (int i = a; i <= b ; i++){ // "a <= b" Has to be: i <= b
sum += i;
}
return sum;
}
}
I think this is want you want.
The result will be:
2+3+4 = 9
Related
So I am very new to learning java and I have a sub class which contains the main and a parent class which does all the calculations. I am having problems on how to pass the elements of an array from the main class to the parent class.
Here is my code. Please help me with how to instantiate the array.
import java.util.Scanner;
public class GreatestLeastAverageApp {
public GreatestLeastAverageApp() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
GreatestLeastAverage number = new GreatestLeastAverage();
int[] x = {0};
int a = 0, b = 0;
x = new int[a];
{
for (int i = 0; i <= a; i++)
{
for (int j = 0; j <= a; j++)
GreatestLeastAverage.a[i] = x[j]; // loop to pass the values of the array elements to the parent class from the sub class.
}
}
Scanner keyboard = new Scanner(System.in); // for the input from the user
System.out.println("Enter the number of elements:");
a = keyboard.nextInt(); // enter the number of integers to be entered so loop can run accordingly
System.out.println("Enter a set of integers( Enter -99 to exit):");
do // do loop so the user can input the variables until one of the variable is =-99.
{
{
for (b = 0; b <= a; b++)
x[b] = keyboard.nextInt();
}
} while (x[b] != -99);
//GreatestLeastAverage number = new GreatestLeastAverage(); // object made for parent class.
System.out.println("The Greatest Number is" + number.computegreatest()); // output line.
System.out.println("The Smallest Number is" + number.computeleast());
System.out.println("The average is " + number.computeaverage());
keyboard.close();
}
}
public class GreatestLeastAverage {
static int x; //variables declared for input in super class.
public static int[] a; // static variable to access in both classes.
int temp;
int temp1;
int temp2;
int average;
public int greatestleastaverage(int d) {
d = x;
return x;
}
public static int getarray(int[] b) {
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= x; j++) {
a[i] = b[j];
}
}
return b[];
}
I know you can't return elements of an array but I really need help.
Use Lists. They're generally more flexible, and if you use ArrayList properly, it can be virtually just as performant as an array.
public class GreatestLeastAverage {
// ... other private members
private List<Integer> a = new ArrayList<Integer>();
public List<Integer> getA() {
return a;
}
}
This lets you do code like:
GreatestLeastAverage gla = new GreatestLeastAverage();
for (int b = 0; b <= a; b++) {
gla.getA().add(keyboard.nextInt());
}
If you should require that data for other uses, it's in gla already! Simply reuse it.
for(int a : gla.getA()) {
// Do something with a
}
I'm sure you used static members because you didn't know how to make it work otherwise, but just know that using static members is generally discouraged unless they're final (constant).
You shouldn't pass data (array) to methods in GreatestLeastAverage class by setting the value of the static field (public static int[] a;). Instead you should pass data to methods as theirs arguments. Your program should look like this:
import java.util.Scanner;
public class GreatestLeastAverageApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int numOfElems = input.nextInt();
int[] numbers = new int[numOfElems];
System.out.println("Enter a set of integers:");
for (int i = 0; i < numOfElems; i++) {
numbers[i] = input.nextInt();
}
System.out.println("Statistics:");
System.out.println(" min: " + GreatestLeastAverage.findMin(numbers));
System.out.println(" max: " + GreatestLeastAverage.findMax(numbers));
System.out.println(" average: " + GreatestLeastAverage.findAverage(numbers));
}
}
class GreatestLeastAverage {
public static int findMin(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num < candidate) candidate = num;
}
return candidate;
}
public static int findMax(int[] numbers) {
int candidate = numbers[0];
for (int num : numbers) {
if (num > candidate) candidate = num;
}
return candidate;
}
public static double findAverage(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / (double) numbers.length;
}
}
To make this code even better:
The min/max/average calculations above are not great, e.g. If you pass empty array to findAverage, then numbers.length will be 0 and you'll divide by 0. You should make those calculations better, see: #1, #2, #3.
Consider using ArrayList instead of array, when you need to dynamically change the size of the list during runtime (See Neil's answer).
I have written a code that is supposed to count the following,
here some examples:
x(2) = 1 * (1+2) = 3
x(4) = 1 * (1+2) * (1+2+3) * (1+2+3+4) = 180
x(5) = 1 * (1+2) * (1+2+3) * (1+2+3+4) * (1+2+3+4+5) = 2700
Edit:
Thx a lot so far to everyone!
I didn't expect to get help that fast and precise, really nice :D
Just modified my code now and I no longer get 0 as result (no matter what i typed) which is very good.
But I think there is another mistake left somewhere,
let's say I type into console 2, I will get 2 as result.
If I type 4, I get 24 as result. For 5 I get 120 and 6 I get 720.
From this I could realize one thing.
If i divide let's say 720 by 6, I get 120 which is the previous result (of 5).
And if I take result of 5 which is 120 and divide it by 4, I get 24.
public class CounIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}
Two problems:
b remains 0 in the function x(int), so this function always returns 0. Shouldn't it be initialised to 1?
The function a(int) returns the input parameter. Didn't you mean to return j?
Also, having single character function names makes your program tricky to read.
Because you initialized b to zero every multiplication of b will give you 0
b = 0; // Set b to zero
for (c = 1; c <= k; ++c)
b = b * a(c); // b will stay to 0 because b = 0 * a(c);
Modify your code to
b = 1; // <---- Here the modification
for (c = 1; c <= k; ++c)
b = b * a(c);
To be sure that your code works as expected you should unit test your functions. Take a look at TDD metodology, it will save you a lot of time for bigger projects. And here a link to a nice tutorial to unit tests.
Try this:
public class CountIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i < k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}
This function is very suitable for recursion:
public class SumPyramid {
public static void main (String[] args) {
System.out.println(sumPyramid(5));
}
public static int sumPyramid(int height) {
if (height == 1) {
return 1;
}
else
return height + sumPyramid(height - 1);
}
}
}
Both functions a and x have errors. Modify functions as below.
Logically its working
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i) // changed consition to less than or equal to
j = j + 1;
return j; // returns j
}
public static int x (int k)
{
b = 1; // changed initial value to 1
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
I was given directions to write a method that takes two parameters. If the first parameter is equal to second parameter. Multiply both and print result.
If the first parameter is less than the second parameter, add the two and print the result 10 times.
If the first parameter is greater than the second parameter, subtract the first parameter from the second and print the result 50 times.
This is what I've coded:
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
}
Can you help me with the errors? Thanks!
Problem #1
public class IfHomeworkRedo {
{
public static void two(int a, int b) {
There are two {{ before the two method declaration, you need to get rid of one
public class IfHomeworkRedo {
public static void two(int a, int b) {
Problem #2
You're missing a closing } after the end of the two method...
public static void two(int a, int b) {
if (a == b) System.out.println(a*b);
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
//??? Add } here
As general advice, it's easier to wrap all logic in a {...}, even it's just one line, as it will make it easier to read and reduce the risk on introducing logic errors, for example...
public static void two(int a, int b) {
if (a == b) {
System.out.println(a * b);
} else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a + b);
}
} else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b - a);
}
}
}
There should be no public on the class (if using ideone), and you had misplaced brackets. Solution: (http://ideone.com/7wBaSF)
class IfHomeworkRedo {
public static void main (String[] args)
{
two(3, 3);
two(3, 4);
two(4, 3);
}
public static void two(int a, int b) {
if (a == b) {System.out.println(a*b);}
else if (a < b) {
for (int i = 0; i < 10; i++) {
System.out.println(a+b);
}
}
else if (a > b) {
for (int i = 0; i < 50; i++) {
System.out.println(b-a);
}
}
}
}
The task of exercise is to make a method that will work like in Example.( We must use for loop. But if you know how to do it in another way, it will be also very interesting.) Input number can be any.
Example:
Input: 3
Output:
**1**
*121*
12321
*121*
**1**
My example:
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
for (int i = 0; i < n ; i++)
{
for(int j = 1; j <=d; j++){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
System.out.println("");
}
My output:
****1****
***121***
**12321**
*1234321*
123454321
I can't make the next step, to turn it upside down. Dose anybody hava an ideas?
I have solved this exercise, but I think it is not a perfect solution. Does anybody have another way to solve this task?
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
int k = n*2;
int g = -1;
for (int i = 0; i < d ; i++)
{
if(i<n){
g++;
}
else{k=n*2;
g--;}
for(int j = 1; j <=d; j++){
if (i < n){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
else{
k--;
int abs = Math.abs(k-n);
System.out.print(abs>g ? "*" : g-abs+1);
}
}
System.out.println("");
}
}
}
Output:
****1****
***121***
**12321**
*1234321*
123454321
*1234321*
**12321**
***121***
****1****
When I run Countdown.class I get the following output:
263845041
-1236909152
-973064111
2084994033
1111929922
-1098043341
13886581
-1084156760
-1070270179
2140540357
Blast Off!
The numbers before "Blast Off!" ought to be the first 10 Fibonacci numbers. My source code is as follows.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return 1;
return fib(n-1) + fib(n-2);
}
public static long fastfib(int n) {
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i <= n; n++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
and the class that implements the fastfib method is:
public class Countdown {
public static void countdown(int n) {
if (n == 0) System.out.println("Blast Off!");
else {
System.out.println(Fibonacci.fastfib(n));
countdown(n - 1);
}
}
public static void main(String[] args) {
countdown(10);
}
}
Though your fastfib() method returns long, the calculations are done on ints.
You are encountering integer overflow.
Make sure to declare a,b,c as longs and NOT as ints. If you want even larger numbers (that are out of range for longs as well) - you might want to have a look on BigInteger (and use it).
EDIT: As mentioned by #ExtremeCoders in comment, there is another issue in the code in your for loop:
for (int i = 0; i <= n; n++) should be for (int i = 0; i <= n; i++), you want to increase i - not n.
In addition to the other answers,
for (int i = 0; i <= n; n++) {
should be
for (int i = 0; i <= n; i++) {
// ^ that's an i
Change the datatypes of a,b and c to long, and it will start working fine. Your numbers are crossing the limits for int.
You should user BigInteger insted of long
import java.math.BigInteger;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
int result = n.compareTo(BigInteger.valueOf(1)); // returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
if (result != 1) return BigInteger.valueOf(1);
return fib(
n.subtract(
BigInteger.valueOf(1).add
(n.subtract
(
BigInteger.valueOf(-2)
)
)
)
);
}
public static BigInteger fastfib(int n) {
BigInteger a = BigInteger.valueOf(0);
BigInteger b = BigInteger.valueOf(1);
BigInteger c = BigInteger.valueOf(0);
for (int i = 1; i < n; i++) {
c = a.add(b);
a = b;
b = c;
}
return c;
}
}