How use a global variable in if statement - java

I have this if statement and what to access axeMinDmg. How do i set it as a global variable to so that i can access it within the if statement. Also, how to i set minDmg as a global variable so that i can access outside of the if statement. thanks
// if yes ask what weapon to purchase
if (name.equals("yes")){
System.out.println("Select Your Weapon \n axe \n bat \n sword : \n ");
Scanner wc = new Scanner(System.in);
String weapon = wc.next();
if(weapon.equals("axe")){
minDmg = axeMinDmg;
} else {
System.out.println();
} // close if statement

Global variables really does not exists in Java. You can create a public static final member of a class and the member will accesible in the same scope as the class (if public everywhere)
public class MyClass {
public static final int axeMinDmg = 20;
can be used as MyClass.axeMinDmg from everywhere.
Another way could be to go with an Enum.

You can declare and initialize it outside the
if (condition) {
}
block. This will allow you to use it within if.
e.g.
String minDmg = null;
String axeMinDmg = null;
if (name.equals("yes")) {
...
}
Hope I am answering your question as intended.

You can initialize it in the beginning of your class, so the if statement would be included in its scope.

Related

How to deal with an unitialized constructor in an if statement (Java)

I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.

Is there a way to force a variable out of existence in Java?

Basically, my goal is to be as efficient as possible by "deleting" variables when I'm done with them, even if still in scope. So far, I've been using if(true) to manually create a scope that defines the lifetime of variables, but I'm looking for something like, var.close(), a function that's only purpose is to cause a variable to essentially go out of scope and no longer have a memory location reserved for it.
The example I use below could obviously use for() to sidestep this particular instance(the assignment wants me not to use for()), but my concern is wider than variables used as indexes.
(ignore any other logic/syntax errors present, as I haven't proofread this yet)
package root;
import javax.swing.JOptionPane;
public class DebugEight4
{
public static void main(String[] args)
{
String array[] = new String[100];
String entry = " ";
final String STOP = "/']";
StringBuffer message = new StringBuffer(
"The words in reverse order are:\n"
);
if(true)
/*
*forces x out of scope
* after while statement ends
*/
{
int x = 0;
while(!entry.equals(STOP))
{
entry = JOptionPane.showInputDialog(null,
"Enter another word\n" +
"Enter " + STOP + " when you want to stop");
if(!entry.equals(STOP) && x != 100)//prevents fragmentation error
{
array[x] = entry;
}
else
{
JOptionPane.showMessageDialog(null, "That\'s all! Let's see the results.");
}
++x;
}
}/* end x scoping if
* If the if(true) wasn't here, x would still exist!
*/
for(int y = array.length-1; y > 0; --y)
{
message.append(array[y]);
message.append("\n");
}
JOptionPane.showMessageDialog(null, message);
}
}
Any thoughts?
This is exactly what scopes are for. You don't need to invent your own scoping system. Any variable should be declared in the smallest possible enclosing scope. But that's as far as you need to go with this. It is a visibility principle, not an efficiency principle, as all the stack needed for a method is allocated on entry to the method, and inner scopes don't correspond to bytecode instructions in any way.
To create a more-limited scope is easy enough. Just create a new block:
public static void whatever() {
int a = 5; // Exists until end of method
{
int b = 5; // Exists until end of outer block
{
int c = 5; // Exists until end of inner block
}
// c is no longer accessible
}
// b is no longer accessible
}
I'd recommend against this for a few reasons:
It's harder to read for little gain
The compiler or JIT can automatically figure out the lifetime of variables and automatically handle what you're attempting to do
You can't overlap variable lifetimes this way (nesting means that the most-nested variable must expire off the stack before less-nested ones)

How do I use the values of variables that are calculated inside a method, in a class?

I'm very new to programming, and don't understand much. I've been trying to build a simple game where a user and computer compete by rolling dice to earn points. My method is posted below. The computer is only allowed to earn 20 points per turn.
My issue is that I need the value of variable computerTotal to be remembered after the method has been called and completed. I want to ensure that whenever the computerTurn method is finished, I can use that calculated variable computerTotal outside of that method.
I tried establishing a new int in the .java file class (but outside of the method), and then using that int within the method to hold the value, however I receive errors about the integer needing to be static?
This is all very confusing to me. Can anyone help me out?
public static void computerTurn()
{
System.out.println("Passed to Computer.");
Die computerDie1, computerDie2;
int computerRound, computerTotal;
computerRound = 0;
computerTotal = 0;
while (computerTotal < 21){
computerDie1 = new Die();
computerDie2 = new Die();
computerDie1.roll();
computerDie2.roll();
System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n");
computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue();
int cpuDie1Value;
int cpuDie2Value;
cpuDie1Value = computerDie1.getFaceValue();
cpuDie2Value = computerDie2.getFaceValue();
System.out.println ("Points rolled this round for the Computer: " + computerRound);
computerTotal = computerTotal + computerRound;
System.out.println ("Total points for the Computer: " + computerTotal + "\n");
}
Any variables created inside a method are "local variables" meaning they cannot be used outside the method. Put a static variable outside of a method to create "global variables" which can be used anywhere.
Add a method to your class
public static int getComputerTotal() { return ComputerTotal;}
Then you can get the value outside of the class by doing something like:
ComputerTurn();
ComputerTurn.getComputerTotal();
Putting the variable outside of the method is on the right track, but since this method is static (meaning it cannot access variables that depend on object instances), it can only access static variables. Declare computerTotal in the class, outside of methods, using the following:
private static int computerTotal;
You should probably do some research on object-oriented programming and what static means in Java.
Declare computerTotal as a member variable of your class, so that its value is available even outside the function.
class MyClass{
private int computerTotal ;
public void function myFunction()
{
........
......... // your calculations
computerTotal = computerTotal + computerRound;
}
public int getComputerTotal(){return computerTotal ;}
}
You have to declare the computertotal outside any methods to keep them. so like this:
public class name {
int computertotal = 0; //v=can just uuse int computertotal;
public void method() {
while(computertotal < 20) {
computertotal += 1;
}
}
}
And now he variable gets saved!
You may need to add some setters and getters to get that int from another class.
class NewClass {
private int yourInt = 1;
}
It is telling you to make it a static variable because you may be calling it in a statement like
NewClass.yourInt;
, a static variable is one that’s associated with a class, not objects of that class.
Setters and getters are methods which allows you to retrieve or set the value which is private from another class. You might want to add them in the NewClass, where your int is declared. Setters and getters looks like this.
Setter:
public void setYourInt(int newInt) {
this.yourInt = newInt;
}
Getter:
public int getYourInt() {
return this.yourInt;
}

".class" error in Java

I am trying to run this program but I cannot, the compiler is sending me a ".class" error.
Can somebody help me with my problem and if it is possible a general tip about ".class" error?
Here is the program:
import java.io.*;
class Bus
{
private int kostos;
private int plithos;
private int typepiv;
Bus(int x,int y,int z)
{
kostos=x;
plithos=y;
typepiv=z;
}
public void KB(int[] x)
{
try{
for(int i=1;i<5;i++)
{
if(typepiv==2)
{
plithos=plithos+plithos/2;
kostos=kostos-kostos/2;
}
if(typepiv==3)
{
plithos=plithos-plithos/5;
kostos=kostos-kostos*25/100;
}
if(typepiv==1)
{
plithos=plithos;
kostos=kostos;
}
x[i]=plithos*kostos;
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
class testBus
{
public static void main(String args[])
{
String leof[]=new String[4];
int leof1[][]=new int[4][3];
for(int i=1;i<5;i++)
{
System.out.println("dwste onoma leoforiou");
leof[i]=UserInput.getString();
System.out.println("dwste kostos thesis enilika");
leof1[i][1]=UserInput.getInteger();
System.out.println("dwste plithos thesewn");
leof1[i][2]=UserInput.getInteger();
System.out.println("dwste tupos epibath gia enilikes=1,gia
paidia=2,gia suntaksiouxous=3");
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
----->leof2.KB(KostEnoik);
System.out.print("onoleo");
System.out.print(" ");
System.out.print("plithos");
System.out.print(" ");
System.out.print("kost(EURO)");
System.out.print("typepiv");
System.out.print(" ");
System.out.print("apotelesma kostEnoik");
for(int g=1;g<5;g++)
{
System.out.print(leof[g]);
System.out.print(leof1[g][2]);
System.out.print(leof1[g][1]);
System.out.print(leof1[g][3]);
System.out.print(KostEnoik[g]);
}
}
}
the compiler message says :
testBus.java:56:error:cannot find symbol
leof2.KB(KostEnoik);
symbol:bariable leof2
location:class testBus
1 error
Remove the array brackets [] when invoking KB
leof2.KB(KostEnoik);
and remove the preceding enclosing brace }.
Aside: Java naming conventions indicate that variables start with a lowercase letter e.g. kostEnoik. Also consider giving the method KB a meaningful name, e.g. calculateCost
Read Java naming conventions
concern is with your access
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it is defined i.e. outside for loop and scope is upto for loop and that's why the compiler will not be able to find that varialble .
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it's defined (in this particular case, the for loop) and that's not allowed.
method KB takes an int array as argument, but you don't have to add the [] when passing the argument. The correct line is
leof2.KB(KostEnoik);
However, there's something pretty odd with you logic: you're repeatedly (for loop) setting leof2, but only the last iteration of the loop will have any effect. I'm almost certain that that's not what you actually want, but the correct answer to where Bus leof2 should actually be defined depends on the correction of that issue.
leof2.KB(KostEnoik); this is the main culprit. whether you have imported UserInput.
Also try to go through the Java Basics
any method can be invoked using object when it is non static or class name when it is static. Please consider this link
Get leof2 object out side the For Loop.
Don't type [] when you pass the array as argument "leof2.KB(KostEnoik[]);".

Object not recognized outside if-else clauses

In the if-else branches I declared two different PrintStream objects with the same name. However, when I use the PrintStream object later the compiler says that it "cannot find symbol". Why doesn't it see the object I created? The object works withing the if-else branch it was declared in. Here's the code:
System.out.println("Welcome. Would you like to continue a previous adventure, or begin anew?\n(type: new or old)");
status = scan.nextLine();
if(status.equals("new")) {
System.out.println("What do you call yourself?");
name = scan.nextLine();
System.out.println("And what shall be the title of your saga, after you are gone?");
game = scan.nextLine();
System.out.println("Very well. Prepare yourself, for this is the beginning of your end...\n...\n...\nAre you ready?");
status = scan.nextLine();
System.out.println("Not that it matters. Let us begin.");
status = scan.nextLine();
File file = new File(game + ".txt");
PrintStream print = new PrintStream(file);
print.println(name);
old = false;
} else {
System.out.println("So you're still alive? What was the title of your tale?");
game = scan.nextLine();
File file = new File(game + ".txt");
Scanner gscan = new Scanner(file);
String save = "";
while (gscan.hasNextLine()) {
save += gscan.nextLine();
save += "\n";
}
System.out.println(save);
PrintStream print = new PrintStream(file);
print.println(save);
old = true;
name = scan.nextLine();
}
if(old) {
}
print.println("beans");
You need to declare the variable outside the if statement, and then assign it in the two branches, like this:
PrintStream print;
if (status.equals("new")) {
...
print = new PrintStream(file);
} else {
...
print = new PrintStream(file);
}
Better yet, you can set the file inside the if, and then create PrintStream after the conditional:
if (status.equals("new")) {
...
} else {
...
}
File file = new File(game + ".txt");
PrintStream print = new PrintStream(file);
You are experiencing a scoping problem. You need to declare it outside the if-else statement if you want to use it outside the if-else statement.
There are different levels of scoping in Java programs. A scope is generally defined by a set of curly braces. However, there is also public, private, and protected types that allow for use of more global variables than just inside their braces.
Each of these scopes can have their own variables that are not available elsewhere.
Take a look at these two pieces of code:
String s;
if ( foo ) {
s = "one";
} else {
s = "two";
}
if ( foo ) {
String s = "one";
} else {
String s = "two";
}
In the first one, s is available after the if/else. In the second, s is only available within the {} (if/else blocks). Each block happens to have a variable with the same name, but it isn't the same variable. And it isn't available later.
What happens in a scope stays in the scope.
if(some condition)
{
int x = 10;
}
System.out.println(x);
This will not work because the scope of x is limited only till the if block. If you want it to live outside the if block, then declare it outside the if block.
Why define PrintStream print twice? You need to define it only once in this case outside the if.

Categories