cannot find symbol (calculator) [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I recently made a program to be a calculator but three errors occurred. Here is the code:
import java.util.Scanner;
public class mathyStuff {
public static void main(String[] args) throws InterruptedException {
Scanner raw = new Scanner(System.in);
String input = raw.nextLine();
int y = 0;
while (y < input.length()) {
if (input.substring(y, y+1) == "+" || input.
substring(y, y+1) == "-" || input.substring(y, y+1) == "/" || input.substring(y, y+1) == "*") {
String x = input.substring(y, y+1);
int z1 = Integer.parseInt(input.substring(0,y));
int z2 = Integer.parseInt(input.substring(y+1, 0));
}
else {
y = y + 1;
}
}
math(z1,x,z2);
}
public static void math (int num1, String op, int num2) throws InterruptedException {
if (op == "+") {
System.out.println(String.valueOf(num1 + num2));
}
if (op == "-") {
System.out.println(String.valueOf(num1 - num2));
}
if (op == "*") {
System.out.println(String.valueOf(num1 * num2));
}
if (op == "/") {
System.out.println(String.valueOf(num1 / num2));
}
}
}
Here is the errors:
Compilation Errors Detected
Line: 18
cannot find symbol
symbol: variable z1
location: class mathyStuff
Line: 18
cannot find symbol
symbol: variable x
location: class mathyStuff
Line: 18
cannot find symbol
symbol: variable z2
location: class mathyStuff
I'm currently using a website called browxy, an online java compiler. And yes, I know. Download eclipse. I can't bring my computer everywhere I go so I use this instead.

This is a scope issue.
You can't access x, z1 and z2 because they're declared inside a while loop, but you're trying to access them outside the while loop.
You probably want to move the math function call inside the if block inside the while loop.

You are essentially asking for a variable in a situation where java can't confirm that the variable has been defined. You need to pre-define the variable in a location outside any while loops or if loops that end before the calling of these variables.
Try adding this right before the int y = 0;:
int z1 = 0;
int z2 = 0;
Also, where do you define x? If you mean the string x, you need to write "x" on line 18. If you mean a variable named x, make sure it is defined in the right scope. As it is, I can't find it anywhere.
Side note: your math method can't take "x" as an input for the second variable. It only takes "+", "-", "*", and "/". If you want to be able to use "x", you will need to change your math method.

Related

Cannot find symbol when calling another classes method [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 6 days ago.
I'm working on a program that estimates pi using the Ramanujan series. In the series, it requires me to calculate the factorial of a couple expressions, which I have a class written for. I had used the class for a previous assignment, explaining the tests at the top of the class. My issue comes into play when I try to create the Factorial object to use Factorial.calculate(nthNum). I've tried everything I can think of, searched many forums, went back over my notes, and I cannot figure out why this error keeps happening.
.\Ramanujan.java:9: error: cannot find symbol
Factorial f = new Factorial();
^
symbol: class Factorial
location: class Ramanujan
.\Ramanujan.java:9: error: cannot find symbol
Factorial f = new Factorial();
^
symbol: class Factorial
location: class Ramanujan
2 errors
error: compilation failed
If someone could explain to me why the symbol cannot be found, it would be very helpful. Thank you.
public class Ramanujan {
public static void main (String[] args){
String nthRamNumString = args[0];
int nthRamNum = Integer.parseInt(nthRamNumString);
findRamNum(nthRamNum);
}
public static double findRamNum(int nthNum){
Factorial f = new Factorial();
double factNum = f.calculate(nthNum);
double firstVal = ((2 * Math.sqrt(2)) / 9801);
double piNum = 0;
for (int i = 0; i <= nthNum; i++){
piNum = piNum + (4 * factNum) * (1103 + (26390 * nthNum)) /
(Math.pow(factNum, 4) * (Math.pow(396, 4 * nthNum)));
}
double finalPiVal = (firstVal * piNum);
return 1 / finalPiVal;
}
}
public class Factorial {
public static void main (String[] args){
String value = args[0];
Long n = Long.parseLong(value);
if (n > 20){
System.out.println("Value must be less than 20!");
System.exit(0);
}
else if (n < 0){
System.out.println("Value must be greater than 1!");
System.exit(0);
}
else{
System.out.println(calculate(n));
}
Long result = calculate(0);
if (result == 1){
System.out.println("Factorio.calculate(0) returned " + result + ". Test passed!");
}
else{
System.out.println("Factorio.calculate(0) returned " + result + ". Test failed!");
}
result = calculate(5);
if (result == 120){
System.out.print("Factorio.calculate(5) returned " + result + ". Test passed!");
}
else{
System.out.print("Factorio.calculate(5) returned " + result + ". Test failed!");
}
}
public static long calculate(long n){
long factNum = 0;
if (n == 0){
return 1;
}
else{
for (int i = 0; i <= n; i++){
factNum = factNum + (n * (n - 1));
}
}
return factNum;
}
}
The error message indicates that the compiler cannot find the symbol "Factorial" in your Ramanujan class. This could be because you have not imported the Factorial class in your Ramanujan class, or because the Factorial class is in a different package.
To fix the issue, make sure that you have imported the Factorial class in your Ramanujan class using the "import" statement at the beginning of the file:
(import package.name.Factorial; // replace with the actual package and class name)
Alternatively, you can specify the full package and class name when you create the Factorial object:
package.name.Factorial f = new package.name.Factorial(); // replace with the actual package and class name
Also, note that your Factorial class has a main method, which should not be necessary for a class that is meant to be used as a utility class. You may want to remove the main method from the Factorial class.
I forgot to compile the code :(. Thanks everyone for the help.

Why does this code keep returning a "variable might not have been initialized" error?

I'm new to coding with java, so excuse me if I come off a bit uninformed, but my code keeps returning this error for me:
Main.java:15: error: variable hold might not have been initialized
return hold;
^
My code is as follows:
public class Main
{
public static double calcPostage(double ounces)
{
double hold;
if ((ounces <= 10) && (ounces > 0))
hold = 3;
else if (ounces > 10)
hold = ((ounces-10)*0.15)+3;
else
System.out.print("Invalid input.");
return hold;
}
public static void main(String[] args)
{
double hold;
DecimalFormat form = new DecimalFormat("0.000");
Scanner input = new Scanner(System.in);
System.out.print("Enter how heavy your package is in ounces.\n");
double ounces = input.nextDouble();
System.out.print("It will cost " + form.format(calcPostage(ounces)) + " to mail your package.");
}
}
There might be some other issues in that code as I haven't been able to successfully run it just yet, but I'd truly appreciate it if someone could help me out with this. Thanks!
In the below code :
public static double calcPostage(double ounces)
{
double hold;
if ((ounces <= 10) && (ounces > 0))
hold = 3;
else if (ounces > 10)
hold = ((ounces-10)*0.15)+3;
else
System.out.print("Invalid input.");
return hold;
}
Suppose , if none of the conditions in "if" and "else if" are met, then -- double type variable hold -- doesn't gets initialized. Hence you are receiving the error :
Main.java:15: error: variable hold might not have been initialized
return hold;
^
So it is always better to initialize your variables to assign them a default value or an initial value.
Do this :
double hold = 0.0;
condition where if and else if both condition do not get satisfied else print invalid input but hold in that case is not initialized .
try to put
double hold=0.0;
so that hold get initialized.

Beginner Java program? if, else, while loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to create a program in which the user thinks of a number between 1 and 10, and the computer repeatedly tries to guess it by guessing random numbers. (It's ok to guess the same number more than once) At the end of the game, the program reports how many guesses it made. For example:
I have written the following code:
import java.util.*;
public class Pick {
public static void main(String[] args){
System.out.println("This program has you, the user, choose a number");
System.out.println("between 1 and 10. Then, I, the computer, will try");
System.out.println("my best to guess it.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int result = -1;
int count = 0;
for (i = 1; i <= number; i++){
while(result != number){
result = r.nextInt(10) + 1;
System.out.println("Is it " + r + "? (y/n)");
String yn = console.next();
if(String yn = "y"){
System.out.println("I got your number of " + result + " in " + i + " guesses.");
} else if (String yn = "n") {
count++;
} else {
System.out.println("I got your number of " + result + " in " + i + " guesses.");
}
}
System.out.println();
}
}
I'm confused as to why my program doesn't work? It won't compile and has 7 errors. I think I went wrong in the if/else statements. Should I have used a while loop?
Thanks.
compilation errors by text:
Pick.java:20: error: ')' expected
if(String yn = "y"){
^
Pick.java:20: error: ';' expected
if(String yn = "y"){
^
Pick.java:22: error: ')' expected
} else if (String yn = "n") {
^
Pick.java:22: error: ';' expected
} else if (String yn = "n") {
^
Pick.java:22: error: 'else' without 'if'
} else if (String yn = "n") {
^
Pick.java:25: error: 'else' without 'if'
} else {
^
Pick.java:31: error: reached end of file while parsing
}
^
7 errors
You are trying to use the variable number at for (i = 1; i <= number; i++){ but it doesn't exist. You need to initialize number.
For one thing,
if(String yn = "y") {
}
is not what you think it is in Java. String yn = "y" is an assignment statement, not a comparison.
To compare strings in Java you want to use String's equals() method.
There's are more syntax issues and obvious compiler errors. I suggest you try out one of the many tutorials online for beginning Java.
String yn = console.next();
if(String yn = "y"){
You are declaring yn twice. That's not allowed. Just use yn, no need to speficy it's a String again, you already did.
You're using assignement operator = instead of comparison operator ==. In any case, Strings in Java are not compared using == but using equals method if(yn.equals("y"))
for (i = 1; i <= number; i++)
I don't see the error message for this, but still number is not declared anywhere.

Why my code for checking if a number is a palindrom won't work?

My Java code is here:
import java.util.Scanner;
public class task2 {
public static void main(String args[]) {
System.out.print("Input a 3 digit int");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int isPalindrome = 0;
while (x != 0)
{
isPalindrome = isPalindrome*10 + x % 10;
x /= 10;
}
{
if (x == isPalindrome){
System.out.print ("Yes, this is a palindrome!");
}
else {
System.out.print("No, try again");
}
}
}
}
The code will only recognize a palindrome if the numbers entered are zeroes. I'm having trouble understanding why.
This is because the value of x is getting changed finally.Which is not the original number at the end of the program.
SO take another variable just below x like:
int y = x;
And at the end while using "if" condition use this value of y for comparison rather than using x. It will run perfectly.
int x = scan.nextInt();
int y=x;
if (y == isPalindrome) Add new variable like this.
The problem with you solution is that you modify x in the while loop. Your final check of (x == isPalindrome) will always fail because you will only reach that statement when x is equal to zero.
You need to save the original x value in another variable and use that to check against isPalindrome.
The problem is that in the course of processing the value of x is being changed from what was originally input - it always ends up as 0.
So, you have to preserve the input value, like so:
Scanner scan = new Scanner(System.in);
int original = scan.nextInt();
int x = original;
and then use the original value for the final comparison, like so:
if (original == isPalindrome){
Here's how I'd do it: I'd use the libraries more and write a lot less code.
I'd recommend that you learn the Sun Java coding standards and develop a formatting style. Readability promotes understanding. Style and neatness matter.
package misc;
public class PalindromeChecker {
public static void main(String args[]) {
for (String arg : args) {
System.out.println(String.format("arg '%s' is" + (isPalindrome(Integer.valueOf(arg)) ? "" : " not") + " a palindrome", arg));
}
}
public static boolean isPalindrome(int value) {
String s = Integer.toString(value);
String reversed = new StringBuilder(s).reverse().toString();
return reversed.equals(s);
}
}
When you do the following operation on x:
x /= 10;
you're modifying its value - so it no longer contains the input from:
int x = scan.nextInt();
As Narendra Jadon suggested - you can save the original value into another variable and use it when you try to compare:
if (x == isPalindrome){
Alternative solution that uses "conversion" of the int to String:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}

cannot find symbol- variable y right under my report heading where it says "y=InputNumber"

import java.io.*;
import java.util.Scanner;
public class Project4
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner input = new Scanner(new File("data4.txt"));
PrintWriter out = new PrintWriter(new File("output1.txt"));
out.printf(" Tanner Triggs Project 4\n");
out.printf(" Due 10/18/13 Professor Barker");
y=InputNumber();
int divisor = 2;
ctr = 0;
out.printf("\n For the number %4d the prime factors are", InputNumber);
ctr++;
do
{
int remainder = InputNumber% divisor;
if (remainder = 0)
{
out.print(", " +divisor);
InputNumber = InputNumber/divisor;
}
else
{
divisor++;
}
}while (divisor!=y);
InputNumber = input.nextInt();
out.printf("\n\n%d set of numbers factored" , ctr);
input.close();
out.close();
}
}
You didn't ever declare a variable named y. Java is strongly typed, which means that you have to tell it what type each variable has (in contrast to languages like Ruby or Javascript, where you can put any kind of value in any variable). Add the line int y; above your assignment, or make the assignment int y = InputNumber();.
Additionally, you use two InputNumbers, one method (with parentheses) and one variable (without), but you're never declaring either of those, either. It's generally a bad idea to name both a variable and a method the same thing; it gets confusing in a hurry. Finally, it's customary in Java to lowercase the first letter of method and variable names to distinguish them from class names.

Categories