Beginner Java - Cannot Find Symbol Errors? - java

I've been trying to figure out why this basic java program wont run. I get about 7 cannot find symbol errors. Any help would be much appreciated. I'd love to know what I'm doing wrong.
The program is just some basic calculations that prompt for some input and output data that show what a speeder's fine would be.
import java.io.*;
import java.util.*;
public class Lab1 {
public static void main (String args[]) {
// Create a scanner to read from keyboard
Scanner kbd = new Scanner(System.in);
System.out.print("\nEnter Driver's FIRST Name.");
String firstName = kbd.next();
System.out.print("\nEnter Driver's LAST Name.");
String lastName = kbd.next();
System.out.print("\nEnter Driver's Age.");
int age = Integer.parseInt(kbd.next());
System.out.print("\nEnter the Speed Limit.");
int speedLimit = Integer.parseInt(kbd.next());
System.out.print("\nEnter Driver's Actual Speed");
int actualSpeed = Integer.parseInt(kbd.next());
System.out.print("\nDid violation occur in construction zone? (yes/no)");
String constructionZone = kbd.next();
int speedDifference = (actualSpeed - speedLimit);
if (speedDifference <= 5) {
int baseFine = 0;
}
else if(speedDifference >= 20) {
int baseFine = (speedDifference / 5) * 50;
}
else {
int baseFine = (speedDifference / 5) * 30;
}
if(constructionZone.equals("yes")) {
int constructionFine = 10;
}
else {
int constructionFine = 0;
}
if(age <= 21 && speedDifference >= 20) {
int underageFine = 300;
}
else {
int underageFine = 0;
}
int totalFine = baseFine + constructionFine + underageFine;
System.out.println("Last Name: " + lastName);
System.out.println("First Name: " + firstName);
System.out.println("Driver Age: " + age);
System.out.println("Speed Limit: " + speedLimit);
System.out.println("Actual Speed: " + actualSpeed);
System.out.println("MPH Over Limit: " + speedDifference);
System.out.println("Base Fine: $" + baseFine);
System.out.println("Construction Zone Fine: $" + constructionFine);
System.out.println("Underage Fine: $" + underageFine);
System.out.println("Total Fine: $" + totalFine);
}
}

Your variables baseFine, constructionFine and underageFine are defined within the scope of if statements. Declare them outside of that scope so that they are visible in the scope of the main method. For example
int baseFine = 0;
if (speedDifference <= 5) {
baseFine = 0;
}

baseFine ,constructionFine ,underageFine These 3 variables are not declared properly. You have declared these three within a local scope. But outside of the scope it can not be recognized.
So declare them as class members.
WHAT IS VARIABLE SCOPE
as you are beginner of java so I think you better know about what variable scope is.
The scope of a variable is the part of the program over which the variable name can be referenced.
You can declare variables in several different places:
In a class body as class fields.
As parameters of a method or constructor.
In a method's body or a constructor's body.
Within a statement block, such as inside a while or for block.
Variable scope refers to the accessibility of a variable. You neither can refer to a variable before its declaration nor you can use them outside the scope

You got variable scoping issues
underageFine , constructionFine and baseFine need to be defined outside of the if/elso to be accessible by the rest of the method.

Related

Variable Scope and Visibility in Java

I am making a vacation and vacationdriver. The vacation file will serve as my blueprint and the driver will be the interactive portion of the program creating instances of vacation. I have everything working perfectly, but when I add in the one value I am missing to my print statement of line 47 of the vacation driver class I break the program.
I need to call the value for numSales which I thought is declared in line 42. When I type in numSales on line 47 at the beginning and in the middle of the output as shown I get a red line underneath and Eclipse tells me "numSales cannot be resolved into a variable". What do I need to do to get the value of numSales to be actively output in the print statement on line 47 of the vacation driver?
Here is the vacation class:
package cbrownmod4;
import java.text.NumberFormat;
public class Vacation {
// money formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
// instance variables
private String vacationName;
private int numSold;
private Double priceEach;
// empty constructor
public Vacation() {
}
// partial constructor
public Vacation(String n, int s, double e) {
vacationName = n;
numSold = s;
priceEach = e = 0;
}
// updatSales method
public int updateSales() {
int updateSales = 0;
updateSales = updateSales + numSold;
return updateSales;
}
// totalValue method
public double totalValue() {
double totalValue = 0;
totalValue = totalValue + (numSold * priceEach);
return totalValue;
}
// toString method
public String toString() {
return vacationName + " has been sold " + numSold + " times for " + money.format(priceEach) +
" each for a total value of " + money.format(numSold*priceEach);
}
// getters and setters
public String getVacationName() {
return vacationName;
}
public void setVacationName(String vacationName) {
this.vacationName = vacationName;
}
public int getNumSold() {
return numSold;
}
public void setNumSold(int numSold) {
this.numSold = numSold;
}
public Double getPriceEach() {
return priceEach;
}
public void setPriceEach(Double priceEach) {
this.priceEach = priceEach;
}
}
Here is the vacation driver:
package cbrownmod4;
import java.text.NumberFormat;
import java.util.Scanner;
public class VacationDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// ask for the number of vacations and read it into numVacations
System.out.println("How many vacations are there?:");
int numVacations = input.nextInt();
// ask for the number of sales people and read it into numPeople
System.out.println("How many sales people are there?: ");
int numPeople = input.nextInt();
// beginning of loop for number of vacations
for(int i = 0; i < numVacations; i++) {
//ask for the name and price and read these into variables
System.out.println("What is the name of vacation #" + Integer.toString(i+1) + "?:");
String name = input.next();
System.out.println("How much does " + name + " cost?: ");
Double price = input.nextDouble();
// create a Vacation instance using the data obtained above
Vacation vacay = new Vacation (name, i, price);
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
int numSales = input.nextInt(); // line 42
// call updateSales with this number
numSales = vacay.updateSales();
} //end of inner loop
//where line 47 begins
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were sold for " + money.format(price) + " for a total of " + money.format(numSales * price));
} //end of outer for loop
} //end of main
}
Due to requests to provide a snippet of the portion of the code not working here is the bit thats proving me problems:
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were
sold for " + money.format(price) + " for a total of " +
money.format(numSales * price));
NOTE: If you take out the numSales in the snippet of the vacation driver, the program executes correctly but does not have the correct output because it is missing the necessary output variable
The clear concise question would be - why doesn't numSales work when I use it like shown in the short snippet. Again my problem is that Eclipse says "numSales cannot be resolved into a variable."
The problem is that you declare numSales inside a for {} block.
You need to declare it before the for block:
int numSales = 0; // set initial value in case numPeople is 0 and the loop never runs
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
numSales = input.nextInt(); // line 42; this value is never used? it is overwritten below
// overwrite the never-used value from line 42??
numSales = vacay.updateSales();
} //end of inner loop
// now numSales is still visible, because it was declared on this same 'level' and not in an inner block
System.out.println("numSales: " + numSales);
The value set in line 42 is never used, and is overwritten in line 45, so you might as well call input.nextInt(); without setting the value to numSales.

variable need initialization in for loop, but not do while loop?

I just want to calculate your future age. You enter 3 things: your current age, the current year, and the future year. I was experiementing with for and do while loops. Then I came cross this problem, variable currentAge is not initialized. But none of the other variables are initialized either, other variables are fine. The only difference here is others are in the do while loop, but currentAge is in the for loop. Why did this happen? Can somebody explain the difference and why? Please see the below code.
import java.util.Scanner;
public class Lab3Class
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String cleanUpStr;
int currentAge;
int futureAge;
int currentYear;
int futureYear;
for (int cntr = 0; cntr < 3; ++cntr)
{
System.out.print("Enter your current age\t");
currentAge = input.nextInt( );
cleanUpStr = input.nextLine( );
}
if (currentAge >= 0){
do
{
System.out.print("Enter current year\t");
currentYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(currentYear < 0);
do
{
System.out.print("Enter future year\t");
futureYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(futureYear < 0 || futureYear < currentYear);
input.close();
futureAge = currentAge + (futureYear - currentYear);
System.out.println("In the year " + currentYear + " you are " + currentAge + " years old");
System.out.println("In the year " + futureYear + " you will be " + futureAge + " years old");
} else {
System.out.println("Too many tries for an valid age!");
}
}
}
The do / while loop code block is executed once (at least) no matter what the condition is. But the for loop does not follow the same tradition : The for loop checks whether the condition is valid FIRST, THEN it executes.
Execution DEMO:
For loop : (pre; condition; post)
Check the condition -> If condition is true -> 2. Execute code block -> 3. Go on to next iteration
Do / While loop: do { }while(condition);
Execute code block -> 2. Check condition -> If condition is true -> 3. Go on to next iteration.
Try this version of code it's perfect:
import java.util.Scanner;
public class Lab3Class {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String cleanUpStr;
int currentAge = 0;
int futureAge;
int currentYear;
int futureYear;
System.out.print("Enter current age\t");
currentAge = input.nextInt();
if (currentAge >= 0) {
do {
System.out.print("Enter current year\t");
currentYear = input.nextInt();
cleanUpStr = input.nextLine();
} while (currentYear < 0);
do {
System.out.print("Enter future year\t");
futureYear = input.nextInt();
cleanUpStr = input.nextLine();
} while (futureYear < 0 || futureYear < currentYear);
input.close();
futureAge = currentAge + (futureYear - currentYear);
System.out.println("In the year " + currentYear + " you are "
+ currentAge + " years old");
System.out.println("In the year " + futureYear + " you will be "
+ futureAge + " years old");
} else {
System.out.println("Too many tries for an valid age!");
}
}
}
In order to make it works - you just need to change currentAge declaration line setting it to initial value, like this:
int currentAge = 0;
Java initialize class fields with default values, but not methods variables.
As an alternative solution (just to improve understanding) I would recommend to move declaration of currentAge to class level and leave it without default value, like following:
public class Lab3Class
{
private static int currentAge;
...
}
The program behavior will be the same, but will depict difference between field and method variable declaration and initialization.
You may find useful following links:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.1
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5

I don't know why the variables are not initializing, all variables declared inside if statements aren't recognized

I can't figure out why the variables aren't being able to be printed
import java.text.*;
import java.io.*;
public class CoffeeBags
{
//CONSTANTS
public static final double SINGLE_PRICE = 5.5;
public static void main( String[]args)
throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
//Display Message "Enter Number of Bags Ordered: "
System.out.print("Enter Number of Bags Ordered: ");
//Save input as string
String inputStr = br.readLine();
//Verify that input is integer
int numBags = Integer.parseInt(inputStr);
//Make sure number is above 0
if (numBags <= 0)
System.out.print("Please purchase at least one bag.");
if (numBags <= 0)
System.exit(0);
//Calculate purchase price
double purchasePrice = SINGLE_PRICE * numBags;
//Set numBagsLeft to numBags
int numBagsLeft = numBags;
//Determine Number of Large Boxes needed
if (numBagsLeft >= 20) {
int largeBoxCount = numBagsLeft / 20;
}
//Reinitialize Number of Bags to the remainder
int numBagsLeft2 = numBagsLeft % 20;
if (numBagsLeft2 >= 10) {
int mediumBoxCount = numBagsLeft2 / 10;
};
int numBagsLeft3 = numBagsLeft2 % 10;
if (numBagsLeft3 > 0 && numBagsLeft3 <= 5){
int smallBoxCount = 1;
} else {
int smallBoxCount = 2;
}
//Display
System.out.print("\n\nNumber of Bags ordered: " + numBags + " - " + purchasePrice
+ "\nBoxesUsed: "
+ "\n "+largeBoxCount+" Large - $+largeBoxCount*1.80
+ "\n "+mediumBoxCount+" Medium - $"+mediumBoxCount*1.00
+ "\n "+smallBoxCount+" Small - $"+smallBoxCount*.60
+ "\n\nYour total cost is: $"+largeBoxCount*1.80+mediumBoxCount*1.00+smallBoxCount*.60+purchasePrice;;)
}
}
Okay. So the code is supposed to take in a number of "Coffee Bags", and then, using a system of if statements, filter down through in order to find out how many boxes you will need to purchase in order to best save money. The problem I'm having is that the variables such as largeBoxCount and mediumBoxCount are not being initialized, and thus aren't able to be called when I go to print them.
I see some scoping issues. Variables declared inside of an if block are visible only inside the if block and not outside of it. Declare those variables before the if blocks and in the main method.
bar = 0; // declared before the if block, visible inside and out
if (foo) {
bar = 1; // this variable is visible outside of the if block
int baz = 1; // this variable is not visible outside of the if block
}
System.out.println("bar = " + bar); // legal
System.out.println("baz = " + baz); // illegal
You are declaring the variables inside the if statements, when the scope ends they are removed.

How to use variables defined in an if statement outside of it

I have been trying to make a calculator and when I define variables inside an if statement it says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
BlockNum cannot be resolved to a variable
at firsttry.Main.main(Main.java:57)
Now I know that you have to define variables outside of if statements, because of the variable scope, but when I try to do that like so:
package firsttry;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int BlockNum;
BlockNum = 1;
I get the error of:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Duplicate local variable BlockNum
at firsttry.Main.main(Main.java:36)
So how exactly would I fix this problem? From what I have read the only solution for that problem with the variable scope is to define the variable outside of the if statement, but it doesnt seem to work for me?
My full code:
package firsttry;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int BlockNum;
BlockNum = 1;
csv bGather = new csv();
ToolName atool = new ToolName();
Scanner input = new Scanner(System.in);
//Welcoming Message
System.out.println("Welcome to Minecraft Build/excavate calculator"
+ "\nIts suggested you use tools that are suitable for the block"
+ "\nthat you are breaking as its much faster"
+ "");
//GATHERES USER VARIABLES
System.out.println("What block are you gathering? (use minecraft block ids)");
String block = input.next();
System.out.println("What tool are you using , 1 for using hand and up to 4 for diamond");
int tool = input.nextInt();
System.out.println("Do you want to enter the dimensions of the area you are excavating"
+ "or just the exact block number"
+ "1 for dimensions "
+ "2 for exact number");
int TypeOfSelection = input.nextInt();
if (TypeOfSelection == 1) {
System.out.println("Height of the area");
int Height = input.nextInt();
System.out.println("length of the area");
int length = input.nextInt();
System.out.println("width of the area");
int width = input.nextInt();
} else if (TypeOfSelection == 2) {
System.out.println("Exact amount of blocks");
int BlockNum = input.nextInt();
} else {
System.out.println("ERRORRRR");
}
//CSV FILE STUF
String ToolName = atool.NameOfTool(tool);
String blockname = bGather.name(block);
double blockbreak = bGather.speed(tool,block);
input.close();
//Overall calculations
if (TypeOfSelection == 2) {
System.out.println(BlockNum);
}
System.out.println("You are gatherering " + blockname + " using a " + ToolName + " \nand it will take you " + blockbreak + " Seconds per block");
}
}
else if (TypeOfSelection == 2){
System.out.println("Exact amount of blocks");
int BlockNum = input.nextInt();
}
If int BlockNum is the same variable as variable which you declared at the top, remove the int part.
else if (TypeOfSelection == 2){
System.out.println("Exact amount of blocks");
BlockNum = input.nextInt();
}
}else if (TypeOfSelection == 2){
System.out.println("Exact amount of blocks");
int BlockNum = input.nextInt();
}
In above snippet, BlockNum is getting clash with the one in the following code:
int BlockNum;
BlockNum = 1;
Because, inside if, it sees that variable with the same name is already defined,
Solution:
Change name of the variable in either of the case(e.g., use
int BlockNum1 = input.nextInt();) .
you were redeclaring a variable with the same name BlockNum.
if you are referring to the same variable outside the if then just call
}else if (TypeOfSelection == 2){
System.out.println("Exact amount of blocks");
BlockNum = input.nextInt();
}
if you are not referring to the same variable you can rename one of the variable like
}else if (TypeOfSelection == 2){
System.out.println("Exact amount of blocks");
int internalBlockNum = input.nextInt();
}
you cannot create multiple variable in a method with the same name.

Java out of scope

My program is nearly done except for one problem. I'm having an out of scope problem with the for loop. The goal of the program is to compound monthly interest for a user inputted amount & term.
An example of output at $5000 principal with 5% interest for 3 years would be:
Month: Interest: Principal:
1 $20.83 $5020.83
2 $20.92 $5041.75
etc etc etc
Starting Balance = $ 5000.00 // having problem outputting these w/ for-loop
Final Account Balance = $ 5807.36 // System.out.print keeps repeating multiple times
Total Interest Paid = $ 807.36 // but i can't use variables outside of loop
My problem is that during my for loop, I keep outputting Starting Balance, Final Balance and Total Interest every time the program goes through the loop. but if I try to use the variables outside the loop it goes out of scope and if I try to declare variables outside of the loop I can't use them inside the loop because it's already been declared in the constructor.
Can anyone give me some hints or advice?
My code:
public class Calculator
{
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String Month = input.next();
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0) // input validation
{
System.out.println("The term, interest rate and principal must be greater
than zero");
continue;
}
if (!Month.equals("month")) // input validation
{
System.out.println("Please input month after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (Month.equals("month"))
{
for (int month = 1; month <= term; month++)
{
double interest = (principal * interest_rate / 100) / 12;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month,
dollar_sym, interest, dollar_sym, principal );
double start_principal = principal - interest; // problem
double final_principal = principal; // problem
double total_interest = interest * interest_rate; // problem
System.out.println(" Starting balance = " + start_principal ); // problem
System.out.println("Final account balance = " + final_principal ); // problem
System.out.println("Total Interest Paid = " + total_interest); // problem
}
}
}
}
}
Declare them before the loop begins, so they will exist inside the loop and after it:
double start_principal = 0;
double final_principal = 0;
double total_interest = 0;
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error) {
// ...
}
// ...
In my answer, I am assuming that when you say goes out of scope, you mean that you get a compile time error. (note, it would make the answer easier to address if you provided the error message and the line that is causing the error message).
The scope of a variable refers to where the variable is accessible. For example, if you declare a variable inside of an if statement, the scope is that if statement. Some example code:
public void updateStatus(){
Boolean shouldCheckStatus = true;//this variable is declared inside of the updateStatus method, so that is the scope of the variable
if(shouldCheckStatus == true){
Int hitCounter = 0;//this variable is declared inside of the if statement, so it is only accessible inside of the if statement
//do some work
if(hitCounter > 100){
self.registerHits(hitCounter);//hitCounter is still accessible here, because it is still inside of the if statement
}
else{
shouldCheckStatus = false;
}
}//close the if statement and so close the scope...
//the hitCounter variable is no longer in scope, because we are no longer in the if statement
//but shouldCheckStatus is still in scope, because we are still in the method
if(shouldCheckStatus == true){
self.callAnotherMethod();
}
}
So in your problem, you need to declare your variable above where you want to use it, inside of the scope that you want to use it. And then not declare it again. So declare before the loop.

Categories

Resources