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.
Related
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).
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
For my school I need to create a method which moves a bug in any direction. I have the following code:
package Test;
//imports
import java.util.Scanner;
import java.util.Random;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 1;
int i = 0;
do {
BugObj[i] = new ABug(); //creating instance
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________\n" );
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "\n\n");
move();
i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
loop = reader.nextInt();
} while(loop == 1);
}
public static void move() {
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0) {
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
System.out.println(r);
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
Basically all I need to do is use the values of the bugs position with the random number generated in the method. I am really new to java and am unsure how to do it or even if its possible.
Since objects are passed by reference in java, you can just pass your ABug object to the move function and change the horpos, vertpos attributes. so
move(BugObj[i]);
and
public static void move(ABug bug){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
int originalHorpos = bug.horpos
int originalVertpos = bug.vertpos
// Now just change the attributes however you see fit. i am just adding r
bug.horpos = originalHorpos + r;
bug.vertpos = originalVertpos + r
/*by the way, we dont need to use variables for the original values. something like this would also work
bug.horpos += r;
bug.vertpos += r;
i just want to explain that in java when you pass objects, they are passed by reference and hence you have access to all of its members.
*/
System.out.println(r);
}
also, you dont need to declare the Scanner object again inside the move function. you can pass that to the move function as well and then read as many times as you like.
import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.
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.