Jump to content

run time error

- - - - -

  • Please log in to reply
5 replies to this topic

#1
Cruel Hand

Cruel Hand

    Learning Programmer

  • Members
  • PipPipPipPip
  • 109 posts
  • Programming Language:Java
  • Learning:Java, Visual Basic .NET
I made this simple 4 function calculator but I get a run time error saying the variable "answer" isn't initialized, which it clearly is...can someone help? thanks :D

import java.util.Scanner;


public class calc {

	public static void main(String args[]) {

		Scanner number = new Scanner(System.in);

		double function, fnum, snum, answer;

		System.out.print("Enter 1 for mult, 2 for div, 3 for add, 4 for sub: ");

		

		function = number.nextDouble();

		

		System.out.println("Enter first number:");

		fnum = number.nextDouble();

		System.out.println("Enter second number:");

		snum = number.nextDouble();

		

		if(function == 1){

			answer = fnum * snum;

		}

		if(function == 2){

			answer = fnum / snum;

		}

		if(function == 3){

			answer = fnum + snum;

		}

		if(function == 4){

			answer = fnum - snum;

		}

		System.out.println("Answer: " + answer);

	}


}



#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
If all 4 "if's" evaluate to false, then "answer" will never be initialized. The compiler is trying to catch this.

#3
Cruel Hand

Cruel Hand

    Learning Programmer

  • Members
  • PipPipPipPip
  • 109 posts
  • Programming Language:Java
  • Learning:Java, Visual Basic .NET
ohh ok, that's what I thought. So if I made an else statement that restarted the program then would it work?

thanks for the quick reply btw :)

#4
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Yup, that would work, which is probably the best choice.
Or you can initialize the "answer" variable before the if tests. Like setting it equal to -1, or Integer.MAX_VALUE, or whatever.

#5
Cruel Hand

Cruel Hand

    Learning Programmer

  • Members
  • PipPipPipPip
  • 109 posts
  • Programming Language:Java
  • Learning:Java, Visual Basic .NET
how could I tell the compiler to restart the program if function doesn't equal 1, 2, 3, or 4? I looked it up and people said to call the main method but I don't know how to do that.

#6
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
You could use a while loop that runs until function = 1, 2, 3, or 4. After function = 1, 2, 3, or 4 end the while loop.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users