I instantiated a class so that the information that I will input is stored into it. But I having difficulty in displaying the information that is stored. When I compiled it will say that I havent initialized the variable.
public class REPORTS
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int x=choices();
STUDENT stud;
EQUIPMENT equip;
RESERVATION reserve;
switch(x)
{
case 1:
{
// Code here for input
stud = new STUDENT(Studid,Studname,Studcourse,Studlevel);
break;
}
case 2:
{
// Code also here for input
equip = new EQUIPMENT(eqpmntid,qty,eqpmntname);
break;
}
case 3:
{
// Same goes for here input
reserve = new RESERVATION(studentid,equipid1,reservationdate,returndate);
break;
}
case 4:
{
stud.display(); // error here variable might not have been initialized
break;
}
case 5:
{
equip.display(); // same goes here
break;
}
case 6:
{
reserve.display(); // and also here
break;
}
}
Here is the detailed error message:
It seems that you have to change your program behavior; There is one possible syntactic way of casting a new Object to Student at beginning of your code but you will probably get a runtime error. To change the behavior you can initialize objects with arguments that are null or empty or dummy objects based on the arguments that your constructor get and then Set the fields to appropriate values in related switch case; For example your first lines should look like this:
Student stud = new Student("", Null, dummyObject);
Related
I have a small program with a text based user menu. A switch case is doing the input validation for me, because the user only enters integers which I validate.
The menu looks like this:
----------------------
(1) Manage articles
(2) Manage customers
(3) Close
----------------------
Please enter your number:
This menu is created through an extra method.
When I enter 1, I call another method which contains another do-while loop, this time validating the article menu and so on. The second menu looks like this:
Manage articles
----------------------
(1) Show
(2) Add
(3) Change
(4) Delete
(5) Back
----------------------
Please enter your number:
But to switch back to the previous menu, I always create a new instance of my class and call the first method to show the first menu.
The result is: when I switch many times between the menus, I always create a new instance of my program.
I think there are better ways to do such a multiple-layer-reading and like to know how to perform better here.
Update:
package articlemanagement.menu;
import articlemanagement.model.Artikel;
import articlemanagement.verwaltung.ArticleManagement;
import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;
public class UserInterface {
private ArticleManagement articleManagement;
private UserInterface() {
this.articleManagement = new ArticleManagement();
}
public static void main(String[] args) {
UserInterface userInterface = new UserInterface();
userInterface.showDefaultInterface(userInterface);
System.out.println("See you next time!");
}
private void showDefaultInterface(UserInterface userInterface) {
Scanner scanner = new Scanner(System.in);
int input = 0;
do {
System.out.println("Welcome");
System.out.println("----------------------");
System.out.println("(1) Articles");
System.out.println("(2) Customers");
System.out.println("(3) Shop");
System.out.println("(4) End");
System.out.println("----------------------");
System.out.print("Please enter a number:");
input = scanner.nextInt();
switch (input) {
case 1:
userInterface.showArtikelInterface(userInterface);
break;
case 2:
System.out.println("todo");
break;
case 3:
System.out.println("todo");
break;
case 4:
System.out.println("Bye");
break;
default:
break;
}
} while (input != 4);
System.exit(1);
}
/**
* Show overview
*/
private void showArtikelInterface(UserInterface userInterface) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Manage your articles");
System.out.println("----------------------");
System.out.println("(1) Show");
System.out.println("(2) Add");
System.out.println("(3) Modify");
System.out.println("(4) Delete");
System.out.println("(5) Go Back");
System.out.println("----------------------");
System.out.print("Bitte geben Sie eine Zahl für Ihr Menü ein:");
int input = scanner.nextInt();
switch (input) {
case 1: // show
zeigeArtikel();
break;
case 2: // add
System.out.println("todo");
break;
case 3: // modify
System.out.println("todo");
break;
case 4: // delete
System.out.println("todo");
break;
case 5: // back
System.out.println("Going back...");
// bad style?
userInterface.showDefaultInterface(userInterface);
break;
default:
break;
}
} while (scanner.nextInt() != 5);
}
}
But to switch back to the previous menu, I always create a new instance of my class and call the first method to show the first menu.
You're not creating a new instance every time. You created exactly one instance in main and that's it. With that being said, there are some odd design choices that you made.
Design
You have a UserInterface class which has the ability to print some text depending on the context. Two general designs would be:
Static approach (utility/handler/manager...)
public class UserInterface {
public static void main(String[] args) {
UserInterface.showDefaultInterface();
}
private static void showDefaultInterface() {
// ...
showArtikelInterface();
// ...
}
private static void showArtikelInterface() {
// ...
showDefaultInterface();
// ...
}
}
or you can create a type to represent the context if you need more flexibility (doesn't seem so):
interface Context {
void show();
}
and
class UserInterface {
static void showContext(Context context) { context.show(); }
}
Instance approach
public class UserInterface {
public static void main(String[] args) {
UserInterface userInterface = new UserInterface();
userInterface.showDefaultInterface();
}
private void showDefaultInterface() {
// ...
showArtikelInterface();
// ...
}
private void showArtikelInterface() {
// ...
showDefaultInterface();
// ...
}
}
But you have a mix which doesn't make sense in which you pass the instance to itself:
UserInterface userInterface = new UserInterface();
userInterface.showDefaultInterface(userInterface);
and same with the showArtikelInterface method. An instance has access to itself, so no reason to do this in your case (a case where an instance method would take instances of its type can be in data structures where you have chains/links/nodes...).
Loop condition
Another odd thing is your while conditions
while (scanner.nextInt() != 5); // and the other one
where it should be > 5 and < 1. Though I guess this is just your current test code.
Shared resources
Last thing is that you can share the Scanner object between methods instead of creating one each time. Promote it to a field (static or not depending on your design choice).
I have a superclass TetrisPiece, with subclasses for each variation of the piece, i.e.
class PieceI extends TetrisPiece{
}
class PieceJ extends TetrisPiece{
}
etc...
In a different class I have a switch statement based on a random number that creates a random piece
switch(rand){
//I
case 1: {
PieceI pieceI = new PieceI();
break;
}
//T
case 2: {
PieceT pieceT = new PieceT();
break;
}
etc...
default:
break;
}
My intention is to extract the piece that is generated from the scope of the switch statement so I can use it later on in the class.
The switch method obviously does not work because of the scope issue, and I cannot create a superclass array outside of the switch statement because I would have no ability to cast the indices due to randomization.
Any help is appreciated.
Create an instance of the superclass TetrisPiece, and then assign PieceT, PieceI, etc to it inside the switch statement.
TetrisPiece piece;
switch(rand){
//I
case 1: {
piece = new PieceI();
break;
}
//T
case 2: {
piece = new PieceT();
break;
}
etc...
default:
break;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've tried looking at posts on this issue but am still having some trouble with this error in my code. So in the fourth line, I create an instance variable called SongDatabase to access the SongDatabase class. But when I get down to the line, SongDatabase.addNewSong(); under case 1, I get a java.lang.NullPointerException: null error.
Interface class:
public class Interface
{
Scanner console = new Scanner(System.in);
private SongDatabase SongDatabase;
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
private void run() {
switch (userInput) {
case 1:
SongDatabase.addNewSong();
break;
case 2:
SongDatabase.removeSong();
break;
case 3:
SongDatabase.sortSongs();
break;
default:
System.out.println("Please enter a valid number.");
break;
}
}
SongDatabase class:
public class SongDatabase {
Scanner console = new Scanner(System.in);
private Song song1, song2, song3, song4;
public void addNewSong() {
if (song1 == null) {
song1 = getFromUser();
}
else if (song2 == null) {
song2 = getFromUser();
}
else if (song3 == null) {
song3 = getFromUser();
}
else if (song4 == null) {
song4 = getFromUser();
}
else {
System.out.println("The database is currently full. Please delete a song before adding a new one.");
}
}
I've stepped through the debugger and I know that the instance variable, SongDatabase = null, which is probably causing the error? I previously had a line
SongDatabase SongDatabase = new SongDatabase();
SongDatabase.addNewSong();
instead, but I realised this was creating a new SongDatabase object everytime and wiping what I had stored in there so I had to change it. I'd really appreciate a solution because I have no clue, thanks!
You shouldn't give your instance field the same name as the class because that causes Variable shadowing - Wikipedia says (in part) variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. And you could define the reference at declaration like
private SongDatabase songDatabase = new SongDatabase();
Then something like
private void run() {
switch (userInput) {
case 1:
songDatabase.addNewSong();
break;
case 2:
songDatabase.removeSong();
break;
case 3:
songDatabase.sortSongs();
break;
default:
System.out.println("Please enter a valid number.");
break;
}
}
It is null because it is never being instantiated. Create SongDatabase in your main method to get around your original problem:
public static void main(String[] args) {
Interface intFace = new Interface();
SongDatabase = new SongDatabase();
SongDatabase.addNewSong();
intFace.run();
}
To avoid confusion name your variables starting with a lower case letter.
private SongDatabase songDatabase;
This way it is clear that when you write songDatabase you mean the instance and when you write SongDatabase you are referring to the class.
You need to instantiate the instance of the class before you can use it. It seems that you are already aware of this from the question but it is just a matter of where to do it. For a quick fix you can instantiate it at the point where you declare the variable. Later you can look into a better design. Therefore:
private SongDatabase songDatabase = new SongDatabase();
You were getting the NullPointerException as the class variable for SongDatabase have never been instantiated. To initialize the class variables we can use constructor, please see the code details below. Also to avoid the naming confusion we can use this keyword to have better code readability.
import java.util.Scanner;
public class Interface
{
private Scanner console;
private SongDatabase songDatabase;
public Interface()
{
this.songDatabase = new SongDatabase(); // Initialize the SongDatabase class and .
this.console = new Scanner(System.in); // Initialize the console reference with scanner class.
}
public static void main(String[] args)
{
Interface intFace = new Interface();
intFace.run();
}
private void run()
{
System.out.println("1. Add Song");
System.out.println("2. Remove Song");
System.out.println("3. Sort Song");
System.out.print("Please Enter Choice: ");
int userInput = console.nextInt(); // Get the data from user input
switch (userInput)
{
case 1:
this.songDatabase.addNewSong();
break;
case 2:
this.songDatabase.removeSong();
break;
case 3:
this.songDatabase.sortSongs();
break;
default:
System.out.println("Please enter a valid number.");
break;
}
}
}
I am currently in the process of making a calculator for Android (I am not using any tutorials) and am running into an issue.
I have this:
public void buttonOnClick(View v){
int operation;
switch (v.getId()){
case R.id.one:
numberBox.append("1");
break;
case R.id.two:
numberBox.append("2");
break;
case R.id.plus:
operation=1;
break;
case R.id.eq:
if (operation == 1){
// Print value
}
break;
default:
break;
}
}
Note that this is not the exact code, it is just a mockup.
The problem is, with the scope of the case, when the operation is set to 1, it is not set publicly and when I go to read it in the equals case, it is set back to 0.
How can I fix this problem?
You must be new in Java or any other programming language:
local variables are only used in the method they are declared in.
Whenever you go out of the method the variable is destroyed as well as its value.
So each time you enter a new variable is initialized.
To make this work just create a global class variable and use it or
Pass an object to the method that holds some int variable : the current operation, then read/write the variable using that object.
In your case its better to use a global class variable:
public class MyClass {
int operation;
public int getOperation() {
return operation;
}
public void setOperation(int value) {
this.operation = value;
}
.....
THEN:
....
public void buttonOnClick(View v){
...
case R.id.plus:
this.operation = 1;
break;
case R.id.eq:
if (this.operation == 1){
// Print value
}
break;
.....
Hi Im currently learning Java and Im doing an assignment where I need to *create a Menu that calls several methods. I have 3 classes (Contacto,Agenda and Principal). My assignment is trying to evaluate Constructors and Arrays and some other basic theory.
My menu error is: Principal.java:34: error: cannot find symbol while(opcion!=4).*
I already check and my variable "opcion" is declared.
public class Principal{
private static void imprimeMenu(){
Scanner input = new Scanner(System.in);
String mainMenu = ("Choose an option from the menu: \n"
+ "1. Add contact\n"
+ "2. Find contact\n"
+ "3. Search contact\n"
+ "4. Exit");
do{
System.out.println(mainMenu);
int opcion = input.nextInt();
switch(opcion){
case 1:
break;
case 2:
System.out.println("Search");
break;
case 3:
System.out.println("Erase");
break;
default:
System.out.println("Command not recognize");
break;
}
}
while(opcion!=4);
}
public static void main(String[] args){
imprimeMenu();
}
}
And inside the my cases I need to call 3 methods (Add, Search and Erase contacts) that are inside a class called Agenda. The 3 methods are void and receive a parameter. I tried but I get an error where it says I need some parameters:
case 1:
Agenda.addContacto(); and also tried Agenda.addContacto(contacto);
My Agenda class looks like this
public class Agenda{
private Contacto [] contactos;
private int numContactos;
public Agenda(){
this.contactos = new Contacto[10];
this.numContactos = 0;
}
public Agenda(int x){
this.contactos = new Contacto[x];
this.numContactos = 0;
}
public void addContact(Contacto contact){
if(numContactos<contactos.length){
this.contactos [numContactos] = contact;
numContactos+=1;
}
}
Your problem is that opcion is defined inside the loop, so it's scope ends before the closing while.
Move the definition outside the loop to fix the problem:
int opcion = 0;
do{
System.out.println(mainMenu);
opcion = input.nextInt();
switch(opcion){
case 1:
break;
case 2:
System.out.println("Search");
break;
case 3:
System.out.println("Erase");
break;
default:
System.out.println("Command not recognize");
break;
}
} while(opcion!=4);
The correct call of Agenda.addContacto method is indeed Agenda.addContacto(contacto). You need to make sure that contacto is set to an instance of Contacto object before making the call.
You have 2 issues with these programme
1.You need to declare option variable before the while loop.
2.If you want to call Agenda.anyMethod() you need to create an instance/object of the class otherwise you can declare the class Agenda as static.then you can directly call the method as
Agenda.addContacto();