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;
}
} }
Related
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();
}
}
I have a 2 class, one of which extends the superclass.
when I call the sub-class from the main, I get an error because "the method I call isn't a part of the class", but as my programme goes on, it should work
I had to use it only with the casting of class, but my teacher told me that casting should not be used in such a work, so please I'd like to understand where I'm wrong and where I can do better
(Im providing the code of 3 classes, the sub-class, the super-class, and the main)
Main
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type in the number");
int number = in.nextInt();
System.out.print("Type in the name");
String name = in.next();
Test testObj = new Test(number);
testObj = new TestSub(number);
testObj.setNameSub(name);
in.close();
}
}
Super class
public class Test {
protected int number;
protected String name;
public Test(int number){
this.number=number;
}
public void setName(String name){
this.name=name;
}
public String toString(){
return "the name is "+name+"the number is "+number;
}
}
Sub Class
public class TestSub extends Test {
public TestSub(int number){
super(number);
}
public void setNameSub(String name){
setName(name);
}
public String toStringSub(){
return toString();
}
}
The error I get is this:
The method setNameSub(String) is undefined for the type Test
In the main where there is this instruction : testObj.setNameSub(name);
The error here is (as indicated in the comments) that you initialize testObj as Test instead of TestSub, causing the error when the compiler isn't able to find setNameSub() between Test's methods.
So the easy solution is clearly to initialize testObj as a TestSub.
The correct solution that takes advantage of the methods inheritance would be to keep the initialization as it is but to call the method testObj.setName(name) instead, and deleting setNameSub() and toString() methods from TestSub class since they don't add any difference from the methods in the Test class.
I am trying to access the super class variable name from user input.
I am not sure how to have the super class variable name point to the user input. Here is the code for it. Any ideas thank you.
package chapter4;
import java.util.Scanner;
public class VetOffice extends Animal {
public VetOffice(int lifeExpectancy, int weight, String name, Character gender, String type) {
super(lifeExpectancy, weight, name, gender, type);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
//super(name);
//= console.next();
//}
}
}
//}
The thing is you cannot access super class variables in main method. Because it is static method. If you want to access in main() you have to make Animal class name variable to static. Then you can assgin a value directly in main().
Like this:
in Animal class,
static String name;
in VetOffice,
name = console.next();
You can try different ways depending on the thing that you are going to achieve you have to decide,
Is this variable can be declare as static or not? Because static variables common for every object.
Another way you can do this is,
Create getters and setters for Animal class member variables. Then also you cannot access in the main method because also you have to make those methods and variable to static.
As a solution without makinng them static or a new methods even getters and setters in super class you can create default constructor for super class and assign values like below:
If your variable in the super class is private you have to create getters and setters.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
VetOffice pet = new VetOffice();
pet.name = console.next();
System.out.println(pet.name);
}
Note: create default constructor If it is unnecessary to create object from VetOffice or super class seeing that you have to pass values to constructor.
UPDATE:
According to your comment
If your variable in the super class is private do this:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
VetOffice pet = new VetOffice();
pet.setName(console.next());
System.out.println(pet.getName());
}
Another way that you asked for in the comment:
Animal class(partialy implemented to show you)
public class Animal {
int lifeExpectancy;
static int weight;
static String name;
Animal(int lifeExpectancy, int weight, String name, Character gender, String type){
this.weight = weight;
this.name = name;
}
public static String getName() {
return name;
}
public static void setName(String n) {
name = n;
}
}
Then in the main method:
Animal.setName(console.next());
System.out.println(Animal.getName());
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();
}
So far I have the following code:
import java.util.Scanner;
public class HallLanceMemoryCalculator {
private double currentValue;
public static int displayMenu(){
Scanner input=new Scanner(System.in);
int choice=0;
while(choice<1||choice>5){
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Clear");
System.out.println("What would you like to do?");
choice=input.nextInt();
}
return choice;
}
public static double getOperand(String prompt){
Scanner input=new Scanner(System.in);
System.out.println("What is the second number?");
double secondNumber=input.nextDouble();
return secondNumber;
}
public double getCurrentValue(){
return currentValue;
}
public void add(double operand2){
currentValue+=operand2;
}
public void subtract(double operand2){
currentValue-=operand2;
}
public void multiply(double operand2){
currentValue*=operand2;
}
public void divide(double operand2){
currentValue/=operand2;
}
public void clear(){
currentValue=0;
}
public static void main(String[] args) {
double value=getCurrentValue();
}
}
When I try to set double value=getCurrentValue(); at the end, I get an error message "Cannot make a static reference to the non-static method." It says the fix is to make the getCurrentValue() method static as well, but I was told not to make that field static by my professor. Is there a simple solution to this that I am just missing?
A static method belongs to the class, a non-static method belongs to an instance of the class.
When you call getCurrentValue() from main, you get an error because main isn't associated with any instance.
You need to create an instance of the class:
HallLanceMemoryCalculator me = new HallLanceMemoryCalculator();
Then you can call the instance's getCurrentValue():
double value = me.getCurrentValue();
Static means there is one for an entire class, whereas if it is non-static there is one for each instance of a class (object). In order to reference a non-static method from a static context, you need to first create an object for that method to be a part of. So, in your main method (the static context), you need to create a new HallLanceMemoryCalculator object. Once you have the object, you can use the object's methods.
The reason your professor does not want it to be static, is so that you have the ability to have multiple HallLanceMemoryCalculator instances, that each keep track of their own value.
Note, I'm not including any code, because I'm sure your professor would want you to figure out that part on your own.
The Method getCurrentValue() is defined as an ordniary (non-static) method of the class. In order to execute it, you need an instance of HallLanceMemoryCalculator.
So try to instantiate HallLanceMemoryCalculator first:
HallLanceMemoryCalculator calc = new HallLanceMemoryCalculator();
double value = calc.getValue();
In order to make some sense, the example should have a constructor for storing the initial value. E.g.
public HallLanceMemoryCalculator(double initial) {
this.currentValue = initial;
}
In doing so, you can use the following main code:
HallLanceMemoryCalculator calc = new HallLanceMemoryCalculator(10);
int choice = displayMenu();
// some code to get the second operand (you don't need the string as param)
double operand = getOperand("");
// some switch statement to handle the choice
...
double result = calc.getCurrentValue();
Create an instance of your HallLanceMemoryCalculator then call getCurrentValue() or make getCurrentValue() static.
you should use an instance of the class and not the class if you want to call your getter function without setting the attribute static.