I am new to java and am having a lot of issues making a multilevel inheritance program.
I'm trying to make a program where my main class (AU) is broken down into subclasses depending on what the user types.
My issue is when I try to call my second level (Part_Time_Student) subclass from my first level subclass (Student).
Whenever I try to call it, it just recalls the first level subclass(the one I'm currently in).
I noticed that if I make my second level subclass(Part_Time_Student) extend the main superclass(AU) it works, but I would prefer to make it extend student.
I realize this is a very complicated post (especially since I don't know the terminology), but I hope my code is easy enough to follow.
AU.java
public class AU {
Scanner input;
static String name;
static Long numb;
public AU() {
}
public void Name() {
input=new Scanner(System.in);
System.out.println("What is the member's name");
String nam = input.nextLine();
AU.name=nam;
System.out.println(nam +" has been added");
}
public void Phone() {
input=new Scanner(System.in);
System.out.println("What is the member's phone number");
Long number = input.nextLong();
AU.numb=number;
System.out.println(number+ " has been saved");
}
}
Main.java
public class Main {
private static Scanner input;
public static void main(String[] args) {
AU au = new AU();
au.Name();
au.Phone();
while (3==3) {
System.out.println("What is your role at the University?");
input=new Scanner(System.in);
String determ=input.nextLine();
if (determ.toUpperCase().equals("STUDENT")) {
Student student=new Student();
break;
}
else if (determ.toUpperCase().equals("STAFF")) {
break;
}
else if (determ.toUpperCase().equals("FACULTY")) {
break;
}
else if (determ.toUpperCase().equals("TESTER")) {
break;
}
else {
System.out.println("Invalid Response");
}
}
System.out.println("yay");
}}
Part_Time_Student.java
public class Part_Time_Student extends Student {
public Part_Time_Student() {
System.out.println("it switched");
System.out.println(GPA);
System.out.println(Assign);
System.out.println(name);
}
public void tester() {
System.out.println("test");
}
}
Student.java
public class Student extends AU {
static double GPA=5;
static String Assign;
public Student() {
super();
System.out.println(name);
System.out.println("Are you a full-time student or part- student(type part or full)");
input=new Scanner(System.in);
while (3==3) {
String get=input.nextLine();
switch (get.toUpperCase())
{
case "PART":{
Student.Assign="Part";
Part_Time_Student Studentp = new Part_Time_Student();
break;
}
case "FULL":{
Student.Assign="Full";
break;
}
default :{
System.out.println("Invalid ");
}}}
}
public void gpa(String grade,long credits) {
System.out.println(name+numb);
name=name;
}
public void Welcome() {
System.out.println("Welcome Student");
}
}
Output:
What is the member's name
-Test
Test has been added
What is the member's phone number
-540
540 has been saved
What is your role at the University?
-student
Test
Are you a full-time student or part-student(type part or full)
-part
Test
Are you a full-time student or part-student(type part or full)
As you can see the command "Part_Time_Student Studentp = new Part_Time_Student();" is just recalling the student class over an over.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Move your statement Part_Time_Student Studentp = new Part_Time_Student(); out of while loop, infact out of the constructor.
When you are constructing your Student class, and inside when you invoke a constructor of subclass, it in turn calls its super class which is Student, so it goes over and over. So it will keep asking you same question again and again.
Remove the Part_Time_Student constructor from :
case "PART":{
Student.Assign="Part";
// Part_Time_Student Studentp = new Part_Time_Student(); //remove this
break;
}
Change this if condition in your Main class below to:
if (determ.toUpperCase().equals("STUDENT"))
{
Student student=new Student();
if ( student.Assign.equalsIgnoreCase( "Part" ) )
{
Part_time_Student part_time_student = new Part_time_Student();
}
break;
}
Related
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}
I am trying to write a code that uses a menu to call on a method in a different file that is in the same folder.
import java.util.Scanner;
public class BugTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("==Bug Solution==");
System.out.println("Enter the bug's intial position: ");
int pos = input.nextInt();
Bug bug = new Bug(pos);
System.out.println("--Menu--");
System.out.println("1) Change Directions");
System.out.println("2) Move Bug");
System.out.println("3) Exit");
int menu = input.nextInt();
while (menu != 3) {
switch(menu) {
case 1: turn();
break;
case 2: move();
break;
default: System.out.println("Invalid Response");
break;
}
menu = input.nextInt();
}
}
}
I get an error on case 1 and case 2 saying the method is undefined for type BugTest.
In a main method you should always call methods from a given Object (given that they are not static methods). Otherwise the program doesn't know which object's method it's supposed to call. For example create class Bug:
public class Bug{
public Bug() {
}
public void moveLeft() {
// add code here
}
}
Then in your main method call the method by creating an instance of class Bug:
public static void main(String[] args) {
Bug myBug = new Bug();
myBug.moveLeft() ; // calls the method of the myBug object
}
In your case the problem can be solved by calling bug.turn() and bug.move() instead of just turn() and move().
This is my scenario: Bank is a class that provides functionality to get rate of interest. However, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% as a rate of interest.
class bank{
public String name;
int interest(){
return 0;
}
String name(){
name = "bank";
return name;
}
}
//SBI Bank
class SBI extends bank {
int interest() {
return 8;
}
public String name() {
String name;
name = "SBI";
return name;
}
}
//ICICI Bank
class ICICI extends bank {
int interest() {
return 7;
}
String name() {
String name;
name = "ICICI";
return name;
}
}
//Axis Bank
class AXIS extends bank {
int interest() {
return 9;
}
String name() {
String name;
name = "AXIS";``
return name;
}
}
/*Main Class*/
public class head {
public static void main(String args[]) {
String n;
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Enter the bank name");
java.util.Scanner sc = new java.util.Scanner(System.in);
n = sc.next();
/*Conditional Statements*/
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}
if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}
if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
}
}
There are several serious problems here. The one that is troubling you right now is that you don't use else if between your if statements that are supposed to be mutually exclusive. Fixing that would solve your immediate problem.
But the name field of the subclasses is never set. It will be null, unless at some point you manage to call the name() method of the bank base class. That method sets the field to "bank".
To be clear, the subclasses are not setting the name field because in the name() method you have a local variable name which shadows the field.
public String name() {
String name; // this local variable shadows the "name" field
name = "SBI"; // this sets the local variable; the field remains null
return name;
}
One way you could end up calling the name() method of the base class is:
bank b = new SBI();
System.out.println(b);
Even though it's an SBI objects, it calls the method of the base class because the variable is declared to be a bank, not an SBI.
This will print bank and now the name field of that SBI object will be set to "bank", although if you call its name() method, it will still return "SBI". But if you access its name field, you'll see it's "name":
System.out.println(b.name());
System.out.println(b.name);
This will print SBI and then name. This is a recipe for disaster. Finally, I will just note that the name field is public which can lead to further problems, and you are not following the normal Java naming convention that class names start with an upper case letter, fields and variables start with a lower case letter, and constants are in all caps. In particular, class bank should be named Bank. Not following standard naming conventions makes your code harder for other programmers to read and makes it less likely that you'll get help here with your program.
You need to rethink your design. The field should either be protected and set in the constructor, or you should get rid of the field and just return a constant from the name() method, at which point Bank could just be an interface with name() and interest() methods instead of a class. (Or return the name from the toString() method, and make Bank a functional interface (an interface with just one abstract method.)) Finally, you need to use else if for a chain of mutually exclusive if conditions.
Your code is returning the print statement in else because that else is for the last if conditional statement ONLY, that's
if (n.equalsIgnoreCase(a.name()))
It is executing the else block because SBI does not equal a.name
To fix that. You should do this
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}else
if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}else
if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
Although this will solve your problem, I will advice you use switch statement.
USe Else IF Condition and Remembr to Make Vehicle class Abstract
abstract class bank{
public String name;
abstract int interest();
abstract String name();
}
//SBI Bank
class SBI extends bank {
int interest() {
return 8;
}
public String name() {
String name;
name = "SBI";
return name;
}
}
//ICICI Bank
class ICICI extends bank {
int interest() {
return 7;
}
String name() {
String name;
name = "ICICI";
return name;
}
}
//Axis Bank
class AXIS extends bank {
int interest() {
return 9;
}
String name() {
String name;
name = "AXIS";
return name;
}
}
/*Main Class*/
public class Demo {
public static void main(String args[]) {
String n;
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Enter the bank name");
java.util.Scanner sc = new java.util.Scanner(System.in);
n = sc.next();
/*Conditional Statements*/
if (n.equalsIgnoreCase(s.name())) {
System.out.println("SBI rate of Interest is " + s.interest());
}
else if (n.equalsIgnoreCase(i.name())) {
System.out.println("ICICI rate of Interest is " + i.interest());
}
else if (n.equalsIgnoreCase(a.name())) {
System.out.println("AXIS rate of Interest is " + a.interest());
}
else {
System.out.println("Invalid Input");
System.out.println("Enter SBI , ICICI or AXIS");
}
}
}
I'm writing some code for a text based game for my Computer Science class, but I'm having some problems with this code
(java code).
The all the code works until I put in the if/else statements, so I want to know where I should be putting the statements at.
(Error Message)
Code:
import java.util.Scanner;
import java.util.ArrayList;
class Progress {
public String udc;
public String u = "up";
public String d = "down";
public void start() {
System.out.println("Hello.");
}
public void c1() {
Scanner name=new Scanner(System.in);
System.out.println("What's your name?");
System.out.println("Hello "+name.nextLine()+".");
}
public void uod() {
Scanner ud = new Scanner(System.in);
System.out.println("Up or down?");
udc = ud.nextLine();
}
public void uodc() {
System.out.println("going "+udc+".");
}
public void end() {
System.out.println("Press any key to exit");
}
}
public class APGame {
public static void main(String[] args) {
Progress p =new Progress();
p.start();
p.c1();
p.uod();
if (u.equals(udc)) {p.uodc();}
else {p.oud();}
p.end();
}}
u and udc variables are defined inside another class, that is Progress, and should be accessed (as they are public), by p.u and p.udc.
if (p.u.equals(p.udc)) ...
udc and u are instance variables of the class Progress. So the problem with the if-else statement is that you are not referencing udc from any object of the Progress class. To fix it do:
if(p.u.equals(p.udc) {
p.uodc();
}else{
p.uod();
}
I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.