Method help- beginners mistakes - java

import java.util.*;
public class Problem5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Number();
}
}
public int Number() {
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
I'm having a lot of trouble writing methods in terms of the method signature.
The errors I'm getting typically involve "error: class, interface, or enum expected" on the receiving or returning types.
In this case, the errors are on the returning aspect in the method signature and then later within the method when trying to return an int.
Can anyone could explain what I'm doing wrong?

Normally I would reformat the code in a question, but since half of your problem is caused by the fact that the code is not indented, I will reformat it in my answer.
Here's your code reformatted:
import java.util.*;
public class Problem5
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Number();
}
}
public int Number()
{
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
Now it is easy to see that your Number() method is not inside the class definition.
Also, to call your Number() method from a static method, you need to make your Number() method static also.
And thirdly, you need to pass the scanner variable into your Number() method.
Here's the resulting fix:
import java.util.*;
public class Problem5
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Number(scanner);
}
public static int Number(Scanner scanner)
{
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
}
Edit Lastly, as #AndyTurner and #javaguy point out, use Java naming standards - variables and method names start with a lower case letter.

You can't write methods outside the class definition, which you could not spot because of poor indentation of the code, so add your Number() method inside your Problem5 class as shown below:
public class Problem5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Number(scanner);
}
public static int Number(Scanner scanner) {
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
}
Also, note that Number() method should be static in order call it from static main() method. Also, you need to pass the scanner object to the Number() method as an argument (shown above).
As a side note, ensure that you follow Java naming standards i.e., method names start with lowercase like number(), but not like Number()

Related

call variable from another class

static int input;
Scanner scn = new Scanner(System.in);
public BusGenerator(Depot depot)
{
this.depot = depot;
}
public int getinput()
{
return input;
}
public void run()
{
System.out.println("Enter Number of Buses:" );
input = scn.nextInt();
}
I have a class called BusGenerator and from here i ask the user about the number of Bus and the system scans it and save it in the variable called "Input".
I have another class called Depot and i want to call the variable "Input" from the Class depot. Is there a way to do that?
As the code is, you can simply use BusGenerator.input in the Depot class to refer to it (as pointed out in the comments).
However, since you've already defined a getter for this variable, it might be more consistent to make input private and refer to it with the public getter/setter methods.

Can I use non static variable in static method in java?

"write a program in java that declare a class with one integer data member and two member functions in() and out() to input and output data in data member."
My current code is as follows.
import java.util.Scanner;
public class Operator
{
static int a;
public static void input() {
Scanner in=new Scanner(System.in);
System.out.println("Enter the number:");
a=in.Nextint(); //Here is problem
}
public static void output() {
System.out.println("Number is:" + a);
}
public static void main(String[] args)
{
input();
output();
}
}
You seemed to be confused w.r.t instance variables and local variables.
You can always declare a "local variable" inside a static method.
main() for example is a static function and we always declare variables inside it.
So your creation of a variable "in" of type Scanner inside input() function is perfectly fine.
However, you "cannot" access instance variables and instance methods from static methods.
This post on stack overflow gives a full and complete answer: Can non-static methods modify static variables
As far as your code is concerned, there's a minor error in the code.
The function call to read an integer is "nextInt" and not "Nextint". Java generally uses camel-case to define all its methods. So be careful with the method usage.
The modified code should be this:
class Operator
{
static int a;
public static void input() {
Scanner in=new Scanner(System.in);
System.out.println("Enter the number:");
a=in.nextInt(); //this is nextInt and NOT Nextint
}
public static void output() {
System.out.println("Number is:" + a);
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
input();
output();
}
}
short answer - NO
reason is simple too, that is - it will violates the definition of static i.e. accessible in other class without creating a object(also called instance) of the class.
But, what if we try to do static variable in a non-static method ?
In that case, YES we can do that. Because we have to create a instance (object) of the class to use that method. So, that doesn't violates the definition.

Java Language | Error :- non-static variable scan cannot be referenced from a static context [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Customer customer = new Customer();
Customer.method();
}
}
class Customer
{
**Scanner scan = new Scanner(System.in);**
public static void method()
{
System.out.print("Name : "); // error **non-static variable scan cannot be referenced from a static context**
String name = scan.nextLine();
}
}
Question :- while creating an Scanner class object outside the method() there is an compilation error :- non-static variable scan cannot be referenced from a static context but when i define it inside the method() it is working without error Why ?
Question :- How to create Scanner class Object that every class can use that single object which is defined at one place in a program. Is this possible ?
If you want to access the Scanner from a static method, Scanner itself has to be defined static. If you want everybody to have access to the Scanner on the Customer class, define it as public static.
You may want to read up on OOP principles and on the static keyword in Java.
For your first question, you are trying to access a non static variable from a static method. Static methods can be called without having an instance of the class. However, non static variable are created per instance of the class.
For your second question, you can either make your scanner static, and if you want it to be used from multiple classes, then make it public.
class Customer
{
static Scanner scan = new Scanner(System.in);
public static void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}
}
Please check below possible 2 solutions
Solution 1
Scanner scan = new Scanner(System.in);
public void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}
Solution 2
static Scanner scan = new Scanner(System.in);
public static void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}

How do I fix the error where I cannot make a static reference to a non-static input field?

I am learning java. I wrote the following code but I am getting this error "cant make a static reference to a non static input field" in Arrayfunction(), when I try to take input. Why is this so and How can I fix it?
import java.util.*;
public class MultidimArrays {
Scanner input= new Scanner(System.in);
public static void main(String args[])
{
int array[][]= new int[2][3];
System.out.println("Passing array to a function");
Arrayfunction(array);
}
public static void Arrayfunction(int array[][])
{
System.out.println("Inside Array function");
for(int i=0;i<array.length;i++)
{
for(int j=0;j<array[i].length;j++)
{
System.out.println("Enter a number");
array[i][j]=input.nextInt();// error
}
}
}
Scanner is not defined as static therefore is in the wrong scope
Either create the Scanner instance inside Arrayfunction or create your scanner with
private static Scanner input= new Scanner(System.in);
A non static reference is tied to the instances of the class. While all static code is tied to the class itself.
You must add the static keyword.
input in your class is an instance variable (since it's not defined as static), which means that each instance of MultidimArrays has one of it's own. static fields or methods (often referred to as "class variables/methods" are shared between all instances of a class.
Since Arrayfunction is static, it cannot refer to instance members of its class - there is no way for it to know which MultidimArray to use. You can either solve this by making input itself static, or by removing the static qualifier from ArrayFunction and create an instance of your class:
public static void main(String args[])
{
int array[][] arr = new int[2][3]; //typo here, variable needs a name :)
System.out.println("Passing array to a function");
MultidimArray ma = new MultidimArray();
ma.Arrayfunction(arr);
}
The reason for this error is: As you have not created the object the non-static variable input does not exist, so you can not use it.
To fix it you can make input as static
static Scanner input= new Scanner(System.in);
either make your Scanner static and use it inside the static methods or create an instance of the class an access scanner from your static method.
static Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=input.nextInt();// error
}
OR
Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=new MultidimArrays().input.nextInt();// error
}

How to use one array on 2 different classes

I have 2 classes right now, the first class has the arraylist in it. But on the second class when I try to access the arraylist it keeps giving me the red line underneath saying that the variable doesn't exist.
Here is class one...
public class BankMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
BankMain main = new BankMain();
menu();
}
public static void cardNumbers(){
ArrayList<Integer> cardNum = new ArrayList<Integer>();
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
System.out.println("Thank you! You're card number is " +cardNum);
System.out.println("Type 'c' to go back to main menu.");
String value = keyboard.next();
if(value.equalsIgnoreCase("c")){
menu();
}
else if (!keyboard.equals('c')){
System.out.println("Invalid Entry!");
}
}
public static void menu(){
System.out.println("What Would you like to do today?");
System.out.println();
System.out.println("Create Account = 1");
System.out.println("Login = 2");
System.out.println("Exit = 3");
query();
}
public static void query(){
Scanner keyboard = new Scanner(System.in);
double input = keyboard.nextInt();
if (input == 2){
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
main2.loginCard();
}
else if (input == 1){
cardNumbers();
}
else if (input == 3){
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
}
Here is the second class...
public class BankMainPart2 {
public static void loginCard(){
if (cardNum.contains(name)) {
}
}
}
I know I haven't entered anything in the if statement yet on the second class but I'm just trying to get my array list to work on both classes.
The code looks very naive. A very simple answer to your question is
You have not declared any cardNum in BankMainPart2 as global variable or in loginCard as local variable, how do you think it will be available in the loginCard method?
ArrayList<Integer> cardNum = new ArrayList<Integer>();
is local to cardNumbers method.
How can you access it from other class?
A local variable cannot be accessed from outside the method, so first thing, make cardNum class level variable
Make the variable public if you want other classes to be able to access it directly, else make the variable private and create getter method (setter if required).
You can also send the variable when calling the method as argument
If this is class level variable, make it static and use Classname.variable.
--Edit--
As you have asked for details let me give you a quick overview of the different approaches.
A variable declared inside a method is local. as name suggest "local", no one but the method knows there is such a variable. No other method in the class knows about existence of this variable, let alone some outside class.
I say you can make it static, but static should strictly be used for class level storage, not object level. Say a list which is modified by multiple objects of the same class (I hope you know concepts of objects, else go to the basics otherwise it will not be clear). Now as per your example, I guess this is not what you want.
A public variable is generally no - no, only in few cases it will be useful (for example in android programming where performance is utmost important). Normally we will create a variable and provide getter setters. A getter or setter is used normally when we want to give access to the variable, which again does not look like what you want.
Last, the variable is private to you class, but if you want some method to do something about it, you can pass it as argument, this looks the case for you.
Step by step
take the variable out of method and add to class level, note that I removed static from method names
public class BankMain {
private ArrayList<Integer> cardNum = new ArrayList<Integer>();
// rest of code as it is
..
..
BankMain main = new BankMain();
//change
main.menu();
//no need foe static
public void cardNumbers(){
//no need here now
//ArrayList<Integer> cardNum = new ArrayList<Integer>();
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
..
..
//public static void menu(){
public void menu(){
//send the list
//I see there are confusion at times regarding calling of static method.
//please note objectname.staticMethod() or classname.staticMethod() is one
//and same thing. Just that classname.staticMethod() is more clear
BankMainPart2.loginCard(cardNum);
}
and
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
if (cardNum.contains(name)) {
}
}
}
Your method, BankMainPart2.loginCard has not context of "cardNum", it doesn't know what it is (type or value).
In order for the method to be able to act on the array list, you must pass a reference to it, something like...
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
if (cardNum.contains(name)) {
}
}
}
make the cardnum arraylist as an instance variable in BankMain class and extend BankMain in BankMainClass2 and using reference of BankMain you would be able to access cardNum like this
Class BankMain {
public ArrayList<String> cardNum = new ArrayList<String>();
}
Class BankMain2 extends BankMain {
public void method() {
BankMain2 main = new BankMain2();
sysout(main.cardNum.size());
}
}
but the above scenario would only work when cardNum ArrayList in BankMain class is either marked public,protected or default(Nomodifier). it wouldnt work if its marked as private and other non access modifier such as static and final
You can try any one of these
1.Declare the Arraylist as public then import the first class and use the cardNum in the second class
2.Make the cardNum a static var and use it directly in second class as BankMain.cardNum
3.Pass the Arraylist as argument to the second class.
The key problem is in the the way you are trying to create your classes. Your current problem can be solved by answer given by #MadProgrammer. But you should definitly have a look into the Object Oriented Programming Concepts. This section on How to identify and design a Class? should give you some clear pointers.

Categories