How to fix out of scope variables? - java

Here is my code :
import java.util.Scanner;
public class newCode {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String stored = scan.nextLine();
print();
}
public static void print() {
System.out.println(stored);
}
}
I am using eclipse and I am wondering why I cannot do this, I understand it is out of scope or whatever but how can I get this to work without putting my sysout statement in my main function.

You could always pass a value to your print method instead:
// inside of main:
print(stored);
public static void print(String stored) {
System.out.println(stored);
}
The reason you have to is as you describe; stored inside of main is out of scope. Without informing another method of the value you want to use, it has no way to access it.

You can declare your stored at class level :
public class newCode {
static String stored; // You have to declare it static to access directly it in static method or you can also use newCode object if it is not static
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
stored = scan.nextLine();
print();
}

Related

Please, can you tell me the reason why we declare a scanner class object the second time if we want to use it in a method outside the main method?

For example:
static void lod(){
Scanner j = new Scanner(System.in);
String m = j.next();
}
public static void main(String[] args) {
Scanner j = new Scanner(System.in);
String val = j.next();
}
}
Like, why should I declare the Scanner class object again in the method lod before accessing the scanner class in the method Los.
... why we declare a scanner class object the second time if we want
to use it in a method outside the main method?
You do not have to do it and it is also not a clean way to do it. I would use one of the following ways:
Declare the Scanner object as an instance variable. However, you won't be able to use it directly inside a static method (including main) as you can't access a non-static member inside a static method directly. In a static method, you will be able to access an instance variable only through the instance of the class e.g.
import java.util.Scanner;
public class MyClass {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.print("Enter a word: ");
System.out.println(obj.scanner.nextLine());
}
static void lod() {
MyClass obj = new MyClass();
String m = obj.scanner.next();
}
}
Declare the Scanner object as a class variable (i.e. static variable at class level) e.g.
import java.util.Scanner;
public class MyClass {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod() {
String m = scanner.next();
}
}
Pass the Scanner object to the methods being called from main e.g.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod(Scanner scanner) {
String m = scanner.next();
}
}
You don't need to!
You can declare Scanner object at the class level like this,
class Test {
static Scanner j = new Scanner(System.in);
....
}
In Java the objects can be created inside methodsor outside and so they are only for that method or for the whole class but I don't recomend you to do that becouse every time the class is used the method is created even though you're accesing a method that don't uses it. Instead, you can declarate it outside the method and it will be accessible for all the methods from the class, but it will have to be created separately inside every method and they will be destroyed in the end of the method. Example:
class example{
Canstructor name;
public void method1(){
name = new Constructor();
}
public void method2(){
name = new Constructor();
}
}

How can I refer to a variable under a static method in the main method?

My codes are like the following.
public class readfile {
public static void readfile() {
int i = 0;
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
And it works well if I do not refer to the variable i.
(That means it can print out hello.)
So how can I refer i in the main method?
public class readfile {
static int i;
public static void readfile() {
i = 0;
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
As UUIIUI says in comment, if you declare i inside of readfile(), it is valid only inside of the method.
As Murli says in comment, you need a member variable in the class field. And also it must be static one.
You are writing java code in a bad way :
1.First, the class name char in Java is Uppercase so your class need to be named ReadFile.
You cannot use the i variable in your main method, because it's just a local variable of your readFile method, and you have compilation errors, because of the use of i in the main method, and a warning in the readFile method, because you don't use it in the local block code.
Java appear new for you? and you need to learn a litle bit more. There's a full of book or documentation on the web.
Your sample corrected, compiled well and run well :
package stackWeb;
public class ReadFile {
static int i = 0;
public static void readfile() {
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}
You could try this
class readfile {
static int i =0;
public static void readfile() {
System.out.println("hello");
}
public static void main(String[] args) {
readfile();
System.out.println(i);
}
}

Access static variable from a different class

So I have two classes:
A Main class with the public static void main(String args[]) method
and a Voice class that accesses a static variable from that class.
Within the main class are methods that are used by itself, and are required to be static along with some of its variables.
So I have a static variable within the Main class (that's created/filled in the public static void main(String args[]) method. That's why this case is special) which the other class should be able to access.
Here is an example of what's happening:
public class Main(){
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
public class Voice(){
public void doSomething(){
System.out.println(Main.variable);
}
}
Upon calling the doSomething() method in Voice, it leads to a nullPointerException.
I could fix this by passing on the variable variable to the Voice class, but is there a more easy way to fix this in the long run, if for instance, I needed to use more than one static variable from the Main class?
Your code is having syntax error. You can use this
class Main{
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
class Voice{
public void doSomething(){
System.out.println(Main.variable);
}
}
Output will be 5
You should do as follows
public class Main{
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
class Voice{
public void doSomething(){
System.out.println(Main.variable);
}
}

Class inside a class java?

Im doing a question that requires you to make a class customers which will later on be added into an array list in the method of another class. However I am getting an error on the line i marked ERROR, that says:
"No enclosing instance of type Question3 is accessible. Must qualify the allocation with an enclosing instance of type Question3 (e.g. x.new A() where x is an instance of Question3)." And I have no clue why.
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
}
public static void addSale(String name, double price)
{
customers c= new customers(name,price);
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
}
}
You also have to initialize the kbd variable as:
kbd = new Scanner( System.in );
Please review your code using this suggestion and the others above.
A main method is static and thus has static context. No instance of Question3.class is required for a thread to enter that code block. Your class customers is defined inside of Question3. Because it is an inner class, it has implicit access to the fields and methods inside of the Question3 class, but it requires an instance of Question3 to be able to achieve that behavior. You need to move the code you have now in main(String args[]) into a constructor for the class Question3, and create an instance of Question3 in your main method like so :
public static void main(String args[]) {
Question3 myQuestion3 = new Question3();
}
Alternatively as mentioned by others, you could make your customers class static. This will solve the issue by effectively making customers a top level class, but you will lose the ability to implicitly access the fields and methods of its enclosing type, which is the Question3 class.
First off Great job so far. However, there are a couple of errors that I see in the code.
First you class should be a static class. You are trying to use static methods without a static class.
public static class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
Also, you need to create your scanner for the user to input an object.
private static Scanner kbd = new Scanner(System.In);
Do these and your code will work perfectly!
You should change the declaration your class customers to solve this issue.
Currently its a non-static inner class. You should change it to static inner class.
public static class customers
Non-static inner classes refers implicitly to the instance of the container class. Here you trying to create new instance of customer class in a static function, you don't have Question3 instance there.
Just change your inner class to a public static class:
public static class customers {
And the error disappears :)
There are two problems in your code.
First , you have to initialize scanner object by providing System.in parameter to it.
Second , while creating customer object you have to follow proper syntax.
Here is the working code:
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd=new Scanner(System.in); // <---- Notice this
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
System.out.println(a);
}
public static void addSale(String name, double price)
{
// customers c= new customers(name,price);
Question3.customers c = new Question3().new customers(name, price); // <---Notice this
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
} }

How to call my integer from a method in a seperate class

I'm trying to call some integers into a class from a method within another class
public class Variables
{
public void vary()
{
int DSpr
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
This is my code so far, but on DSpr = Integer.parseInt... eclipse gives me an error "DSpr cannot be resolved". Why is it not calling DSpr from Variables ?
" call some integers into a class from a method within another class" makes no sense to me. Variables in a method are local to that method ONLY
I think what you want to do is something like this
public class Variables
{
...
public int DSpr;
}
...
v.DSpr = Integer.parseInt(spr.nextLine());
i.e Make DSpr a public member variable of the Variables class.
It is recommended that you instead make it a private variable and write setter-getter methods for users outside the class to use it.
Try this: in order to access a variable at another class, it must be declared as class variable.
At your Class Variables:
public class Variables{
int DSpr;
public void vary(){
//do assignment here or operation, if you want to create a method
DSpr = 0;
}
}
Then call it on your main class.
int DSpr is declared locally within vary() method and hence can't be accessed outside of that method. even in it's enclosing class Variables
To access a variable in another class, it should be defined as instance field. (or class variable / static variable)
public class Variables
{
public int DSpr;
// OR
// public static int DSpr;
public void vary()
{
}
}
Now, in BattleCalc class you can access as following:
Variables v = new Variables();
v.DSpr = Integer.parseInt(spr.nextLine());
// OR
// Variables.DSpr = Integer.parseInt(spr.nextLine());
here your DSpr variable scope is limited to this method only:
public void vary()
{
int DSpr
}
so it can not be accessed anywhere else.
if you are using elsewhere you need to re-declare like:
int DSpr = Integer.parseInt(spr.nextLine());
You want to assign a value to DSpr from altogether another class. You should declare DSpr as member variable in Variable class and assign it by calling setter in that class.
Your code will be like this.
public class Variables
{
private int DSpr;
public void setDSPR(int DSpr)
{
this.DSpr=DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
Scanner spr = new Scanner(System.in);
try {
v.setDSPT(Integer.parseInt(spr.nextLine())); //This line here
} catch(NumberFormatException ex) {
System.out.print("Invalid Input.!")
}
}
}
Try this..
import java.io.*;
import java.util.*;
class Variables
{
public void vary()
{
int DSpr;
}
}
public class BattleCalc
{
public static void main(String[] args)
{
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
int DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}
Yes You should get errors in above code, Here is my solution
I assume you want to change the variable value in vary(). But I am not sure the usage of this since you are not using the changed value in BattleCalc.
So get and set the integer variable you can use getters and sertters but here I will do minimum modifications to your code to make it easy to understand (so I am not using getters and setters here although it is the ideal way of doing)
public class Variables {
public int DSpr;
public void vary() {
// Change the value of DSpr
DSpr = 10;
}
}
public class BattleCalc {
public static void main(String[] args) {
Variables v = new Variables();
v.vary();
Scanner spr = new Scanner(System.in);
v.DSpr = Integer.parseInt(spr.nextLine()); //This line here
}
}

Categories