The code im working on is intended to accept an input from the user but whenever i run the program, it keeps telling me that there is an error, the java.land.nullexception: null. I dont know what to do!
import java.util.Scanner;
public class HamzasGrocery
{
// instance variables - replace the example below with your own
private Scanner in;
/**
* Constructor for objects of class HamzasGrocery
*/
public HamzasGrocery()
{
Scanner in = new Scanner(System.in);
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void sampleMethod()
{
double choice1;
double choice2;
double choice3;
double choice4;
double choice5;
double total;
System.out.print("Enter item #1: ");
System.out.println();
choice1 = in.nextDouble();
System.out.print("Enter item #2: ");
choice2 = in.nextDouble();
System.out.println();
System.out.print("Enter item #3: ");
choice3 = in.nextDouble();
System.out.println();
System.out.print("Enter item #4: ");
choice4 = in.nextDouble();
System.out.println();
System.out.print("Enter item #5: ");
choice5 = in.nextDouble();
System.out.println();
System.out.printf("%-10s", "Item #'s");
System.out.printf("%-10s", "Cost:");
System.out.printf("%-10s", "Total:");
}
}
Get rid of the Scanner in the "Scanner in = new Scanner.." code in the constructor.
By doing the declaration the way it is right now, you're saying that the in belong to the local scope and thus ignores the instance variable in.
So the constructor should be:
public HamzasGrocery()
{
in = new Scanner(System.in);
}
In your constructor, you are initializing a new Scanner, not your instance variable Scanner. try this:
public HamzasGrocery()
{
in = new Scanner(System.in);
}
Related
I am working on a project for school. at this point i'm just going over board, I would like to run the class bookstoreCreditPersonal if none of the following conditions are true, but I cant get it to work. any suggestions?
import java.util.Scanner;
public class bookstoreCreditPersonal {
public static void main(Object o) {
String studentNamePers;
String userType;
double studentGPAPers;
double bookstoreCreditPers;
Scanner input = new Scanner(System.in);
System.out.print("Please enter 'S' if you are the student, 'T' if you are the teacher, or 'P' if you are the Parent: ");
userType = input.nextLine();
if (userType.equals("S")) {
System.out.println("Greetings student...");
Scanner Sinput = new Scanner(System.in);
System.out.println("Please enter your(The students) first and last name :");
studentNamePers = input.nextLine();
Scanner SSinput = new Scanner(System.in);
System.out.println("Please enter your(The student's) GPA :");
studentGPAPers = input.nextDouble();
bookstoreCreditPers = studentGPAPers * 10;
System.out.println(studentNamePers + ", your GPA is " + studentGPAPers + ", and you have an available bookstore credit of $" + bookstoreCreditPers);
} else if (userType.equals("T")) {
System.out.println("Teacher");
} else if (userType.equals("P")) {
System.out.println("Parent");
} else {
System.out.println("Lets try that again, one character, in capital form only please.");
//created a class that reruns this class
runClassBSCP.call(null);
}
}
}
Here is the class runClassBSCP:
public class runClassBSCP {
public void call() {
bookstoreCreditPersonal.main(null);
}
}
You need to instantiate/create an object of the class. Then you can call the desired method with the object.
runClassBSCP bscp = new runClassBSCP();
bscp.call();
Also, your class names should always start with an uppercase letter: RunClassBSCP, rather than `runClassBSCP'. For more info, check out Code Conventions for the Java Programming Language.
import java.util.Scanner;
public class ATM {
public static void main(String[] args) throws Exception {
String ATM;
ATM myATM = new ATM();
myATM.go();
ifStatement();
//Main method, declares variables and calls the go() and ifStatement() methds.
}
public void go() throws Exception {
int balance;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to online ATM banking\nHow much do you want in your bank account?\nEnter your number");
balance = userInput.nextInt();
//Starts the program and sets a value to the variable "balance".
}
public static void ifStatement() throws Exception {
//Creats if statements that change the outcome of the program depending on what the user as inputte dinto thto the program.
//This has been done using int variables whihc have been converted into strings so that they can communicate wiht the userOption variable, the userOption variable's value has been set to whatever the user inputs int the program.
String Withdraw;
String Deposit;
String Inquire;
String Quit;
String usersOption;
int a = 1;
int b = 2;
int c = 3;
int d = 4;
String s = Integer.toString(a);
String ss = Integer.toString(b);
String sss = Integer.toString(c);
String ssss = Integer.toString(d);
//Declares variables
Scanner userInput = new Scanner(System.in); // Allows user input.
System.out.println("What do you want to do?\n1.Withdraw\n2.Deposit\n3.Inquire\n4.Quit\nEnter your number");
usersOption = userInput.nextLine();//Sets user input to a variable called userOption.
if (usersOption.equals(s)){
System.out.println("*****************************************\n Withdrawl\n*****************************************\nHow much would you like to draw?\nEnter your number");
String withdrawl;
withdrawl = userInput.nextLine();
balance = balance - withdrawl;
}
else {
System.out.println();
}
if(usersOption.equals(ss)) {
System.out.println("*****************************************\n Deposit\n*****************************************\nHow much do you want to deposit?");
userInput.nextLine(); }else {System.out.println();
}
if(usersOption.equals(sss)) {
System.out.println("*****************************************\n Your balance is 100\n*****************************************");
}
else {
System.out.println();
}
if(usersOption.equals(ssss))
{
System.out.println("*****************************************\n Goodbye!\n*****************************************");
System.exit(0); }else {System.out.println();}
}
}
I declared the balance variable in the go() method and now I am trying to store that variable's value in one of my if statements. However, the compiler is telling me that it does not recognize the variable balance. Does anybody know how to resolve this issue?
The reason why you are getting that error is because you are declaring "balance" inside the go() method.
You can set this variable like input in your ifStatement(int balance) or you can define it at the begining of the class.
Just give your balance back from go and give it to ifStatements() as parameter.
Like this go() will return u an integer.
public int go() throws Exception {
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to online ATM banking\nHow much do you want in your bank account?\nEnter your number");
return userInput.nextInt();
}
Like that you can give your ifStatements() a parameter:
public void ifStatement(int balance) throws Exception {
//Creats if statements that change the outcome of the program depending on what the user as inputte dinto thto the program.
//This has been done using int variables whihc have been converted into strings so that they can communicate wiht the userOption variable, the userOption variable's value has been set to whatever the user inputs int the program.
String Withdraw;
String Deposit;
String Inquire;
String Quit;
String usersOption;
int a = 1;
int b = 2;
int c = 3;
int d = 4;
String s = Integer.toString(a);
String ss = Integer.toString(b);
String sss = Integer.toString(c);
String ssss = Integer.toString(d);
//Declares variables
Scanner userInput = new Scanner(System.in); // Allows user input.
System.out.println("What do you want to do?\n1.Withdraw\n2.Deposit\n3.Inquire\n4.Quit\nEnter your number");
usersOption = userInput.nextLine();//Sets user input to a variable called userOption.
if (usersOption.equals(s)){
System.out.println("*****************************************\n Withdrawl\n*****************************************\nHow much would you like to draw?\nEnter your number");
String withdrawl;
withdrawl = userInput.nextLine();
balance = balance - withdrawl;
}else {System.out.println();}
if (usersOption.equals(ss)) {
System.out.println("*****************************************\n Deposit\n*****************************************\nHow much do you want to deposit?");
userInput.nextLine(); }else {System.out.println();}
if (usersOption.equals(sss)) {
System.out.println("*****************************************\n Your balance is 100\n*****************************************");
}else {System.out.println();}
if (usersOption.equals(ssss)) {
System.out.println("*****************************************\n Goodbye!\n*****************************************");
System.exit(0); }else {System.out.println();}
}
Than you could call it like that:
myATM.ifStatement(myATM.go());
Hope that helps
I am attempted to make an object oriented stock system for a theoretical video shop.
I am constantly getting the following error message:
non-static variables xyz cannot be accessed from a static context.
All the info I have found on static contexts has been for when one method is static and the other is not, however none of my methods are static.
In this piece of code I get that error message twice and I don't understand why.
if (enterOption == 1) {
Movie movieNew = new Movie (titleInput, yearInput, directorInput, ratingInput, genreInput);
VideoShop.movies.add(movieNew);
} else {
UI.runUI();
}
I get it from VideoShop.movies.add(movieNew); and the UI.runUI(); method call.
Full method:
public void createMovie ()
{
Scanner sc = new Scanner (System.in);
System.out.println ("Title: ");
String titleInput = sc.next();
System.out.println ("Year: ");
int yearInput = sc.nextInt();
System.out.println ("Director: ");
String directorInput = sc.next();
System.out.println ("Rating [G / PG / M / MA15 / R18]: ");
String ratingInput = sc.next();
System.out.println ("Genre [a - Action/ b - Drama/ c - Comedy/ d - Musical/ e - Family/ f - Documentary]: ");
String genreInput = sc.next();
System.out.println ("Format [VCD/DVD]: ");
String formatInput = sc.next();
System.out.println ("Cost: ");
double costInput = sc.nextDouble();
System.out.println ("Quantity: ");
int quantityInput = sc.nextInt();
System.out.println("Confirm?");
System.out.println("1. Yes 2. No, return to main menu");
System.out.println("Enter option: ");
int enterOption = sc.nextInt();
if (enterOption == 1) {
Movie movieNew = new Movie (titleInput, yearInput, directorInput, ratingInput, genreInput);
VideoShop.movies.add(movieNew);
} else {
UI.runUI();
}
}
It's likely that VideoShop.movies is non-static field. Instead of using VideoShop.movies you should create an object:
VideoShop shop = new VideoShop();
shop.movies.add(movieNew);
The same for UI:
UI ui = new UI();
ui.runUI();
I'm writing a driver class for a piggy bank class that I created. The idea is that it is supposed to add different types of coins (user input) and then total the cents and display them until "X" is input by the user. I think I have the code right, but there is a weird issue where if I use the "countMoney" accessor into the code, it tells me that all of my variables in the driver class are uninitialized. If I remove it, there are no errors shown by Eclipse. I've printed my source and driver class below:
package piggy;
/**
* #author Kevin
*
*/
import java.util.Scanner;
import piggy.PiggyBank;
public class PiggyBankTester {
/**
* #param args
*/
public static void main(String[] args) {
String num = "str", num1;
int count = 0;
int money;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
PiggyBank total = new PiggyBank();
System.out.println("Welcome to the Piggy Bank Tester");
System.out.println("What type of coin to add (Q, H, D or X to exit)?");
num1 = scan.nextLine();
num = num1.toUpperCase();
{
if (num.equals("X"))
System.out.println("Goodbye.");
else if (num != "X")
{
System.out.println("How many do you wish to add?");
count = scan.nextInt();
if (num.equals("Q"))
total.addQuarters(count);
else if (num.equals("H"))
total.addHalfDollars(count);
else if (num.equals("D"))
total.addDollars(count);
else if (num.equals("X"))
System.out.println("Goodbye.");
}
}
{
total.calculate();
money = total.countMoney();
System.out.println("The piggy bank now contains " + money + " cents.");
}
}
}
You don't need (String Q,D,H,X) .
Also you have declared this variables without give them any value just name.
A way you can do it is to change your if-else statements and set , for example if you want num to be equal to Q ---> if (num.equals("Q") ) <---
I have been struggling for weeks with this issue. I cannot get a result for my calculations. I have all the methods within my Calculating class and have the user input within the Main class. Additionally At the end of my Main class I have created an object to inherit all the calculations from the Calculating class to get the results based on the inputs. It does not work. Any suggestions is highly appreciated.
//Calculating Class
public class Calculating { //Calculation class
//Declaring fields - Inputs
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Accessors and Mutators
//Methods used to calculate Average mass of the vehicle
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}
//Setters
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}
}
//Master class
public class Master extends Calculating{ //Master class
public static void main( String args[] ) //Standard header for main method
{
UserEntry input = new UserEntry(); //Creating object from UserEntry class
//User entry for Total Impulse with exception handling
Double totalImpulse = null;
while(totalImpulse==null){
System.out.print("\nPlease enter Total impulse delivered: "); //System print line for input
try {
totalImpulse= input.gettotalImpulse(); //Instantiates totalImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Average Impulse with exception handling
Double averageImpulse = null;
while(averageImpulse==null){
System.out.print("Please enter Average Impulse delivered: "); //System print line for input
try {
averageImpulse= input.getaverageImpulse(); //Instantiates averageImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Time Ejection charge fires with exception handling
Double timeEjectionChargeFires = null;
while(timeEjectionChargeFires==null){
System.out.print("Please enter Time ejection charge fires: "); //System print line for input
try {
timeEjectionChargeFires= input.gettimeEjectionChargeFires(); //Instantiates timeEjectionChargeFires from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the empty vehicle with exception handling
Double massEmptyVehicle = null;
while(massEmptyVehicle==null){
System.out.print("Please enter The mass of the empty vehicle: "); //System print line for input
try {
massEmptyVehicle= input.getmassEmptyVehicle(); //Instantiates massEmptyVehicle from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the engine with exception handling
Double engineMass = null;
while(engineMass==null){
System.out.print("Please enter The mass of the engine: "); //System print line for input
try {
engineMass= input.getengineMass(); //Instantiates engineMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Fuel mass with exception handling
Double fuelMass = null;
while(fuelMass==null){
System.out.print("Please enter The mass of the fuel: "); //System print line for input
try {
fuelMass= input.getfuelMass(); //Instantiates fuelMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//Outputs based on user inputs
Calculating Master = new Calculating(); //Creates object of Calculating class
System.out.println("\nThe average mass of the vehicle: " +Master.theAverageMassOfTheVehicle() /1000);
}
}
The problem is with your constructor.
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
You are never passing any parameters, so how are you initalizing them?
A better constructor could be:
public Calculating(double totalImpulse, double averageImpulse,
double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) {
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
Your Master class doesn't have to extend Calculating.
All you have to do within your main is to create a Calculating object initialized with the parameters you are taking from input.
Calculating calculations = new Calculating(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass);
Then you can call calculations.theAverageMassOfTheVehicle()