Program 1:
public class ValAndRefTypes {
public static void main(String[] args) {
int x=5;
addOneTo(x);
System.out.println(x);
}
static int addOneTo(int num){
num=num++;
return(num);//Outputs 5
}
Program 2:
public class ValAndRefType1 {
public static void main(String[] args) {
int a=2,b=3;
System.out.println("The sum is: " + Add(a,b));
}
static int Add(int num,int num1){
num++;
num1++;
return(num+num1); //Outputs 7
}
Why does the first program not output the incremented value of the variable 'x', but the second program outputs the incremented value of variables 'a' and 'b'?
I also would like to ask whether this has any relation with Value types and Reference types.
TIA for the answer!
Two reasons:
First:
In the first program, the addOneTo function is adding the value and returning the new value (well, attempting to, but we'll get to that below), but that returned value is ignored:
addOneTo(x);
You don't assign the new value to anything. Assign it back to the variable:
x = addOneTo(x);
Whereas in the second program this works because you are using the returned value. You're including it as part of the output:
System.out.println("The sum is: " + Add(a,b));
Second:
This line is very misleading, and is confusing the logic being implemented:
num=num++;
num++ increments num, but evaluates to the previous value of num. So the assignment results in assigning back that previous value. This could work instead:
num = ++num;
Though that's still clouding the logic for no reason. Just increment directly:
num++;
or if you prefer being more explicit:
num = num + 1;
In the second example, that's how you increment:
num++;
num1++;
In your first program, you are printing "x" which has value 5. Only calling a function does not change the value of "x". If you want to print incremented value the program looks like this:
public class ValAndRefTypes {
public static void main(String[] args) {
int x=5;
System.out.println(addOneTo(x));
}
static int addOneTo(int num){
num=num++;
return(num);//It returns 6 not 5
}
Let me make a small change to program 1. You can't mutate a primitive.
public static void main(String[] args) {
int x=5;
int y = addOneTo(x);
System.out.println(y);
}
static int addOneTo(int num){
num=num++;
return(num);
}
Related
this is such a simple problem but for some reason, I cant wrap my head around Array of Objects or Object Arrays. All I have to do is take in 5 user inputs, and create a class called Height, create object array and store user inputs into obj array and print the average. I'm kinda stuck.
class Height{
int total=0;
int count=0;
public Height(int y) {
total=total+y;
count++;
}
public void print() {
System.out.print("The average is: "+total/count);
}
}
public class ObjectArray {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter 5 heights in inches: ");
int[] x=new int[5];
int total=0;
for(int i=0;i<x.length;i++) {
x[i]=s.nextInt();
}
Height[] h=new Height[x.length];
for(int y=0;y<x.length;y++) {
h[y]=new Height(x[y]);
}
h.print();
}
}
Maybe I'm over complicating it. The problem right now is that I cannot invoke h.print();. I've tried different iterations, ex: taking out the print method and doing all the printing after every iteration.
Your approach is wrong. Your Height class appears to be responsible for the evaluation of the mean value. Hence, you should put all values inside a single Height instance, instead of generating a new instance for each user value.
However, h is an array of Heights object, while print() method is defined on a single Height instance. In order to call such method, you have to access one of the objects contained in h, that is h[0].print().
I'm assuming that your goal is simply to print the average of all the heights recieved via user input.
Your code in your main method is a tad confusing, so correct me if I'm wrong in any of the examples I give here. You should, instead of creating the x[] array, simply add the user input for the five values to Height.total in a for loop, and increase the Height.count variable by one each loop through. This should look something like this:
for (int i = 1; i <= 5; i++) {
// System.out.println("Please enter the next height: ");
Height.total += s.nextDouble();
Height.count++;
}
Then, you can run Height.print();.
I would also recommend adding a System.out.print(""); command to let the user know that they should enter the next value. That's the comment I left in the example code I gave above.
You have to design your Height in a way that match your requirement :
you need different Height with for each one a value
you need to know how many instances there is
For that, you need a private value, and a static counter :
class Height {
private int value = 0;
private static int count = 0; // static => nb of instances
public Height(int y) {
value = y;
count++;
}
public static int averageOf(Height... heights) {
return Arrays.stream(heights).mapToInt(h -> h.value).sum() / count;
}
}
To get the average, because it doesn't depend on a particular instance, you can have a static method, that sums all the value of the Height given and divide by the nb of instance
And use like :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int nb = 5;
System.out.println("Enter " + nb + " heights in inches: ");
Height[] heights = new Height[nb];
for (int i = 0; i < heights.length; i++) {
heights[i] = new Height(Integer.parseInt(s.nextLine()));
}
System.out.println("Average is " + Height.averageOf(heights));
}
I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the
x1=x0-f(x0)/f(x0) also needs a loop
Here's my code currently :
import java.util.Scanner;
public class NewtonsMethod {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your guess for the root:");
double x = keyboard.nextDouble();
double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
for(x=x-f(x)/f(x));
System.out.println("Your answer is:" + guessRootAnswer);
}
}
You've misstated how newton's method works:
The correct formula is:
xn+1 <= xn-f(xn)/f '(xn)
Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.
If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.
The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:
class Newton {
//our functio f(x)
static double f(double x) {
return Math.sin(x);
}
//f'(x) /*first derivative*/
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Stop if you're close enough
int max_count = 200; // Maximum number of Newton's method iterations
/* x is our current guess. If no command line guess is given,
we take 0 as our starting point. */
double x = 0;
if(argv.length==1) {
x= Double.valueOf(argv[0]).doubleValue();
}
for( int count=1;
//Carry on till we're close, or we've run it 200 times.
(Math.abs(f(x)) > tolerance) && ( count < max_count);
count ++) {
x= x - f(x)/fprime(x); //Newtons method.
System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
}
//OK, done let's report on the outcomes.
if( Math.abs(f(x)) <= tolerance) {
System.out.println("Zero found at x="+x);
} else {
System.out.println("Failed to find a zero");
}
}
}
I'm getting some errors in code I wrote for an assignment, and I can't quite understand them.
I:\Java Programming\FibonacciJDialog.java:19: error: variable sum might not have been initialized
return sum;
^
I:\Java Programming\FibonacciJDialog.java:20: error: unreachable statement
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" ); // Display results in dialog box.
^
I:\Java Programming\FibonacciJDialog.java:25: error: missing return statement
}
^
3 errors
Tool completed with exit code 1
Here is the code:
import javax.swing.JOptionPane;
public class FibonacciJDialog {
public static long main(String[] args) {
String num;
int n;
int sum;
num = JOptionPane.showInputDialog("Enter n: "); // getting user number input.
n = Integer.parseInt(num);
Fibonacci box = new Fibonacci(); // Creating new Fibonacci object.
JOptionPane.showMessageDialog(null, "That Fibonacci Number is"); // Display results in dialog box.
return sum;
System.exit(0); // Terminate
}
}
This is the Fibonacci class I made.
public class Fibonacci {
int Fib(int n) {
int in1 = 1, in2 = 1;
int sum = 0;//initial value
int index = 1;
while (index < n) {
// sum=the sum of 2 values;
// in1 gets in2
// in2 gets sum
// increment index
}
return sum;
}
}
You never assign a value to sum.
sum = box.fib(n);
In your main function, you also return the value instead of outputting it to the console.
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" + sum);
A few errors I've noticed:
You don't assign sum a value. It's only declared, but not initialized. That's what the stack trace tells you - you have to initialize the value to something.
I'm willing to bet that the "unreachable code" is a red herring - after you initialize your variable I don't see any code path that won't take you to newing your Fibonacci class.
For some reason, you've decided to return long from main(). I'm not sure how that's working - you may have some other main method somewhere else that calls this class - but you can either return a long, or set the signature of the method to void.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
i am new in java.i want to write a program to swap 2 nos.
i have written 2 programs on it.one is running and other is not.
i cant understand the fault of the not running program.pls help me to understand my fault.
here i giving you both the programs along with the output.
the running program:
public class SwapElementsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
swap(num1, num2);
}
private static void swap(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
}
}
the output is:
before swapping
value of num1 is : 10
value of num2 is : 20
after swapping
value of num1 is : 20
value of num2 is : 10
in the above mentioned program i have not any problem.
but in the next program what is the fault i cannot find.
pls help me to find the error.
class Swap
{
public static void main(int a, int b)
{
int c=0;
c=b;
b=a;
a=c;
c=0;
System.out.println(a);
System.out.println(b);
}
}
in the execution there is no error msg.
but in runtime there is a error msg and that is:
exception in thread "main" java.nosuchmethoderror:main
pls let me know the problem of this program.
public static void main(int a, int b) is not correct.
It must be:
public static void main(String[] args). This is by definition.
If you want to get the first and second argument:
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
problem lies here
public static void main(int a, int b)
Java always starts executing program from the main method you declared in the first sample code.
When you start your java application, the java interpreter tries to find a method
public static void main(String[] args)
to run the application.
In one class you can declare several methods with the same name but with different parameters they get. Like that:
public static void main(String[] args) {
}
public static void main(int a, int b) {
}
public static void main(float a, float b) {
}
And all these methods will be accepted by compiler. Because every method is not identifying by its name only, but by its name and signature. Signature is based on the parameters you pass to a method. Type of every parameter and parameters sequence are the signature body.
So, when you start your app without public static void main(String[] args) method inside, then interpreter is unable to find the main method with expected signature String[] args, and throws the exception.