Cannot find symbol when I've defined it already - java

I'm making a Guess the Number game, and this is my code for the game.
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
int guess, diff;
Random random = new Random();
Scanner in = new Scanner(System.in);
int number = random.nextInt(100) + 1;
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("(including both). Can you guess what it is?");
System.out.print("Type a number: ");
guess = in.nextInt();
System.out.printf("Your guess is: %s", guess);
diff = number - guess;
printf("The number I was thinking of is: %d", guess);
printf("You were off by: %d", diff);
}
}
However, when I try to compile it, it comes up with the following error:
Guess.java:20: error: cannot find symbol
printf("The number I was thinking of is: %d", guess);
^
symbol: method printf(String,int)
location: class Guess
Guess.java:21: error: cannot find symbol
printf("You were off by: %d", diff);
^
symbol: method printf(String,int)
location: class Guess
2 errors
What is wrong with the code?

I assume you are trying to call the printf method of the System.out object. That would look like:
System.out.printf("You were off by: %d", diff);
You need to make the method call using the right object target: in general the method call syntax is "receiver . method name ( parameters )". If the receiver is the current object, it can be omitted.

Related

Java class error Main.java:3: error:

I keep getting this error message I have checked my file names, and my public class is the same as my .java file. Besides checking that I have no idea where to go.
Main.java:3: error: class ClassGenderPercentages is public, should be declared in a file named ClassGenderPercentages.java
public class ClassGenderPercentages
^
Here is my code
import java.util.Scanner;
public class ClassGenderPercentages
{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
int maleStudents, femaleStudents;
int totalStudents;
double maleStudentPercentage, femaleStudentPercentage;
maleStudents = keyboard.nextInt();
System.out.println("Enter number of male registered:" + maleStudents);
femaleStudents = keyboard.nextInt();
System.out.println("Enter number of female registered:" + femaleStudents);
totalStudents = (int) (maleStudents + femaleStudents);
maleStudentPercentage = ((100 * maleStudents) / totalStudents);
femaleStudentPercentage = ((100 * femaleStudents) / totalStudents);
System.out.println("The percentage of males registered is: " + maleStudentPercentage + "%");
System.out.println("The percentage of females registed is: " + femaleStudentPercentage + "%");
}
}
Your files is named Main.java, your class ClassGenderPercentages.
You can rename your file to ClassGenderPercentages.java
(that is already said in the error you received from the compiler)

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

Why am I getting a "cannot find symbol" when I compile?

EDIT:
you guys are really fast at answering. I love it.
I can not believe I missed the fact that I tried instantiating the NumberFormat class meanwhile when I previously used it, I didn't do that. I stared at this code for so long too. Looks like I have a lot to learn when it comes to paying close attention to detail.
Thanks, everyone.
I'm using the NumberFormat class (or method, I'm still getting used to the terminology), but when I compile the program I get a "cannot find symbol" pointing at the decimal in "NumberFormat.getPercentInstance();" but I don't underhand why. Here's the code:
import java.util.Scanner;
import java.text.NumberFormat;
public class StudentAverages
{
//----------------------------------------------------------------
// Reads a grade from the user and prints averages accordingly.
//----------------------------------------------------------------
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
NumberFormat fmt = new NumberFormat.getPercentInstance();
System.out.print("Enter the name of the first student: ");
String name1 = scan.nextLine();
int lab1, lab2, lab3, min = 0;
System.out.print("Enter the lab assignment grades of "+name1+": ");
lab1 = scan.nextInt();
lab2 = scan.nextInt();
lab3 = scan.nextInt();
System.out.print("Enter the project grades of "+name1+": ");
int proj1 = scan.nextInt();
int proj2 = scan.nextInt();
System.out.print("Enter the midterm grade of "+name1+ ": ");
double mid1 = scan.nextDouble();
System.out.print("Enter the final grade of "+name1+": ");
double fin1 = scan.nextDouble(); // fin used so as to not confuse with CONSTANT final
double avgLab1 = (lab1 + lab2 + lab3) / 3;
double avgProj1 = (proj1 + proj2) / 2;
double grade1 = (25 * avgLab1 + 40 * avgProj1 + 15 * mid1 + 20 * fin1) / 10000;
System.out.println();
System.out.println("Student's name " + name1);
System.out.println("Lab average for "+name1+": " + avgLab1);
System.out.println("Project average for "+name1+": " + avgProj1);
System.out.println("Total grade for "+name1+": " + fmt.format(grade1));
New at coding. Thanks for any help. I cross referenced the syntax from the book I'm using, and it checks out. I even checked previous code, and I did nothing differently, or at least nothing that I can see. So why would the compiler say it cannot find the symbol?
Instead of:
NumberFormat fmt = new NumberFormat.getPercentInstance();
it should be:
NumberFormat fmt = NumberFormat.getPercentInstance();
because, you want to call the static method getPercentInstance from class NumberFormat.
Furthermore (as Pshemo said), the NumberFormat class is abstract, so you cannot instantiate it with the new keyword.
Remove the new from:
NumberFormat fmt = new NumberFormat.getPercentInstance();
You are calling a static method.
Remove new keyword in line
NumberFormat fmt = new NumberFormat.getPercentInstance();
NumberFormat is abstract class which means you can't create instance of it.
You need instance of class which extends it, and such instance you can get for instance via getPercentInstance method.

Initialization and FileNotFoundException errors

I am a new Java student and am writing a program that consists of a main method, a class file, two input .txt files, and an output.txt file. The main method should ask the user what the account balance and annual interest is and import deposit and withdrawal information from their respective files, and then to display all calculations from the class file in an output file.
I had originally written this file to ask users for all of this input using the scanner and now I'm trying to get it to work using files as input...which is not going so well.
Main method:
import java.util.Scanner;
import java.io.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
//declare variables
double interest;
double startAmount;
double amountDeposit;
double amountWithdraw;
double d, w;
String filenameInputW, filenameInputD, filenameOutput;
PrintWriter oFile;
File wFile, dFile;
Scanner iFile;
Scanner key = new Scanner(System.in);
//get initial balance
System.out.println("Enter initial account balance: ");
startAmount = key.nextDouble();
//create SavingsAccount class object sending starting amount to constructor
SavingsAccount money = new SavingsAccount(startAmount);
//get annual interest rate
System.out.println("Enter annual interest rate: ");
interest = key.nextDouble();
//send interest rate to class
money.setInterest(interest);
//Retrieve withdrawals from withdrawal.txt
filenameInputW="withdrawal.txt";
wFile = new File (filenameInputW);
iFile = new Scanner (wFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountWithdraw += num;
if(amountWithdraw >= 0.1)
w++;
}
//send to SavingsAccount class
money.withdraw(amountWithdraw);
//Retrieve deposits from deposit.txt
filenameInputD="deposit.txt";
dFile = new File (filenameInputD);
iFile = new Scanner (dFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountDeposit += num;
if (amountDeposit >= 0.1)
d++;
}
//send to SavingsAccount class
money.deposit(amountDeposit);
//display retults
filenameInputW="output.txt";
oFile=new PrintWriter (filenameOutput);
oFile.println("The ending balance is: " + money.getBalance());
oFile.println("The total amount of withdrawls are: " + w);
oFile.println("The total amount of deposists are: " + d);
oFile.println("The annual interest rate is: " + money.getInterest());
}
}
My class file
/**
* #(#)SavingsAccount.java
*
*
* #author
* #version 1.00 2013/5/6
*/
public class SavingsAccount {
//variables
private double interest;
private double balance;
//Constructor
public SavingsAccount(double b)
{
balance = b;
interest = 0.0;
}
//Accessors
public void setInterest(double i)
{
interest = i;
}
public void setBalance(double b)
{
balance = b;
}
//Mutators
public double getInterest()
{
return interest;
}
public double getBalance()
{
return balance;
}
//Withdraw method
public void withdraw(double withdraw)
{
balance = balance - withdraw;
}
//Deposit method
public void deposit(double deposit)
{
balance = balance + deposit;
}
//Adding monthly interest to the balance
public void addInterest()
{
double x = ((interest/12) * balance);
balance = balance + x;
}
}
I get these errors:
--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:46: error: variable w might not have been initialized
w++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:50: error: variable amountWithdraw might not have been initialized
money.withdraw(amountWithdraw);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:62: error: variable amountDeposit might not have been initialized
amountDeposit += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:65: error: variable d might not have been initialized
d++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:69: error: variable amountDeposit might not have been initialized
money.deposit(amountDeposit);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: variable filenameOutput might not have been initialized
oFile=new PrintWriter (filenameOutput);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:75: error: variable w might not have been initialized
oFile.println("The total amount of withdrawls are: " + w);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:76: error: variable d might not have been initialized
oFile.println("The total amount of deposists are: " + d);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:37: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (wFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:55: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (dFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
oFile=new PrintWriter (filenameOutput);
^
12 errors
Process completed.
I'm not looking for handouts, this is my first post for help here but I know you guys wont solve this for me...I just need to learn how to do this properly. I just have no idea why the initialization is having a problem (all mentioned variables are initialized) and the files are located in the same folder.
I think you are confused about the difference between initialization and declaration. The variables that give errors are indeed declared, but they don't have an initial value.
Take a look at w++. This means: add 1 to w. But what is w? You didn't define that.
The same problem is true for d, amountWithdraw and amountDeposit
Also, new scanners with a file as input need a try-catch statement for a FileNotFoundException.
Finally, I think you meant filenameOutput="output.txt"; in stead of filenameInputW="output.txt";
--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
Well, you declared variable amountWithdraw as double, but compilator don't know what is value of this variable and he can't add num. So after declaration you need to initialize amountWithdraw. It can be like this:
amountWithdraw = 0;
It's so simple.
From your code you write the following at the very top: double amountWithdraw; and that's it. This is not an initialization, but a declaration.
The same applies if your girlfriend starts talking about kids, right? If she declares "I want kids" it's not the same as if she "initializes" (gives birth to) a baby. Both might be equally stressful, but in different ways.
You need to either type double amountWithdraw = 0.0; or add the following before modifying the value: amountWithdraw = 0.0;. That will fix the first of your handful of problems.
Edit: For the wrongs...
You should be giving those variables values when you declare them. i.e. int w = 0 etc.
Dirty quick fix: As for the other exception-related errors, for simplicity you can just put public static void main(String[] args) throws FileNotFoundException to get things working in the interim.
Proper fix: Usually though, you should look to handle a FileNotFoundException in a catch block, as it's not good practice to rethrow exceptions willy-nilly.

Having errors with Java assignment

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.

Categories

Resources