Having errors with Java assignment - java

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.

Related

I am having trouble running a java program that calculates the gcd of two numbers with a try /catch exception

I try to calculate the gcd without an exception but the 1st time I executed the code, it said I needed an exception for numbers divided by zero. When I added the try/catch exception, it still wouldn't calculate by gcd. Here is my code:
import java.util.Scanner;
public class methodone {
public static void main(String[] args){
int factor1;
int factor2;
int r;
Scanner input=new Scanner(System.in);
System.out.println("Enter 1st factor");
factor1=input.nextInt();
System.out.println("Enter 2nd factor");
factor2=input.nextInt();
while(factor1!=0){
try{
r = factor1 % factor2;
factor1 = factor2;
factor2 = r;
}
catch{
System.out.println("can't divide by zero");
}
}
System.out.println("GCD is"+factor1);
}
}
What am I doing wrong
try{
r = factor1 % factor2;
factor1 = factor2;
factor2 = r;
}catch (Exception e){
System.out.println("can't divide by zero");
}
edit: This does what you want.
static int gcd(int a, int b)
{
while(a!=0 && b!=0) // until either one of them is 0
{
int c = b;
b = a%b;
a = c;
}
return a+b; // either one is 0, so return the non-zero value
}
There is an answer already that provides a correct algorithm for your problem. I think it is important to make another point here:
An Exception is there to handle exceptional situations. Division by zero is something you can easily anticipate and check, i.e. it is not an exception. That means for your code: don't catch the Exception but check parameters explicitly bofore you divide anything.
This will also avoid the very annoying and unnecessary situation that an Exception is thrown for another reason and you still alert the user that you "can't divide by zero".

I am getting a Cannot find symbol error that I can't resolve

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

Explaining about prints output ordering of recursive loop?

Can anyone please explain the print order of the recursive loop?
import java.util.Scanner;
public class DecimalToBinary {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int decimalNum;
int base;
base = 2;
System.out.println("Enter a nonnegative integer in decimal: ");
decimalNum = console.nextInt();
System.out.println();
System.out.println("Decimal " + decimalNum + " = ");
decToBin(decimalNum, base);
System.out.println(" binary");
}
public static void decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
decToBin(num / base, base);
System.out.print(num % base);
}
}
}
Num % base must print reverse order like this:
why is the order of calls as shown? (Please help me revise my question, English is my foreign language)
Your printing occurs after the recursion. Using (25, 2) as an example, the order of your calls with printing looks like
decToBin(25, 2):
decToBin(12,2):
decToBin(6,2):
decToBin(3,2):
decToBin(1,2):
decToBin(0,2):
print(0)
print(1%2)
print(3%2)
print(6%2)
print(12%2)
print(25%2)
Removing the recursive calls and just leaving the print statements shows the order you are getting:
decToBin(25, 2):
print(0)
print(1%2)
print(3%2)
print(6%2)
print(12%2)
print(25%2)
If you want the printing to be in the reverse order, move the print statement before the recursive call:
public static void decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
System.out.print(num % base);
decToBin(num / base, base);
}
}
New recursion with printing:
decToBin(25, 2):
print(25%2)
decToBin(12,2):
print(12%2)
decToBin(6,2):
print(6%2)
decToBin(3,2):
print(3%2)
decToBin(1,2):
print(1%2)
decToBin(0,2):
print(0)
New output:
decToBin(25, 2):
print(25%2)
print(12%2)
print(6%2)
print(3%2)
print(1%2)
print(0)
the order of the output is reversed
because once the dectobin function is called
decToBin(int num, int base) {
if (num == 0) {
System.out.print(0);
} else if (num > 0) {
it reaches the line
decToBin(num / base, base);
where it postpones its execution and calls "another instance" of the dectobin function with decreased number parameter, before getting a chance to output anything(in the code below)
System.out.print(num % base);
}
then this subsequent call of dectobin is stopped at the same line and another "instance" is started with even smaller num. and so on and so on. none of the "instances" so far gets a chance to print anything.
at some point the "instance" of the function which was started last, recognizes that its
num argument has decreased under value of 1; and since num is integer type, once it is positive but less than 1 it is "Rounded" to 0. so that the following condition is true:
if (num == 0) {
System.out.print(0);
then this last instance behaves differently from all its predecessors. instead of postponing its execution and creating a new "instance" it prints '0' in the line above and just ends returning the execution point to the one "instance" which called it, which then continues to run from the line it was postponed.
then this "instance" outputs its number
system.out.print(num % base);
and ends itself returning the execution to the one which was starting it. and so and so on.
the bottom line is: the function "instance" which started last had the first output.the one which started first had the last

Number Generator with User Input

Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code:
import java.util.*;
public class NumberGenerator
{
// Begin
public static void main(String[] args){
Scanner input;
int max, min, range;
Random gen;
public static int genRandom(int mod){
Random r = new Random();
}
input = new Scanner(System.in);
System.out.println("Please enter a max value: ");
max = input.nextInt();
// Ask user to input max value
System.out.println(" Please enter a minimum value: ");
min = input.nextInt();
// Ask user to input min value
range = Math.abs(r.nextInt()) % (max - min + 1) + min;
// Get random integer between min and max values using %
System.out.println(" Your generated number is: " + range );
}
}
Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another).
Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.
Following Code Will Work. Basically you have a non final method inside main method.
import java.util.Random;
import java.util.Scanner;
public class NumberGenerator {
// Begin
static Random r = new Random();
public static void main(String[] args) {
Scanner input;
int max, min, range;
Random gen;
input = new Scanner(System.in);
System.out.println("Please enter a max value: ");
max = input.nextInt(); // Ask user to input max value
System.out.println(" Please enter a minimum value: ");
min = input.nextInt(); // Ask user to input min value
range = Math.abs(r.nextInt()) % (max - min + 1) + min;
// Get random integer between min and max values using %
System.out.println(" Your generated number is: " + range);
}
}
Your method,
public static int genRandom(int mod){
Random r = new Random();
}
is inside of your main method. You can't declare one method inside of another just like that. You should declare it outside of your main method. Also, you've declared it to return an int, which means you actually have to make it return an int or it won't compile. So do it like this:
public static int genRandom(int mod){
Random r = new Random();
return r.nextInt(); // Add this line to return an int.
}
public static void main(String[] args) {
...
// Call getRandom() in here where appropriate
}
NOTE
The gist of this answer is to help you understand why your code isn't compiling. Even if you get your code to compile, it still probably won't behave correctly. The other answers give you good solutions to make it work correctly.
You declare an object:
Random gen;
Then you create a method called genRandom(int mod) which instantiates a new Random object 'r'. Which is INSIDE your main method. Which isn't correct.
Then when you go to call a method to get a random number you choose to use 'r' which is not in the scope of the statement.
Developers don't let developers code recklessly.
Now I'ma need to take your keyboard.
try this
public class RandomRange {
public static void main(String[] args) {
int min = 50;
int max = 100;
for (int i = 0; i < 10; i++) {
int rnd = (int) ((Math.random() * (max + 1 - min))) + min;
System.out.println(rnd);
}
}
}

Newton's Method Java

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

Categories

Resources