Good day, is there a more efficient way to do this problem with recursion than using a switch statement. In my courses class I have a recursive association of course and a prerequisite then a set the preReqs in the PreReqs class. How can I print out all of preReqs of a class when a user enter a class which has preReqs? Right now I am in the process of using a switch statement and printing each preReq individually but is there a better way to do this still using recursion?
An example out of this: If the user types that course, all of the preReqs will print out too.
ACS-3947 Algorithm Design
prereq: ACS-2947 Data Structures and Algorithms
ACS-2947 Data Structures and Algorithms
prereq: ACS-1904 Programming Fundamentals II
ACS-1904 Programming Fundamentals II
prereq: ACS-1903 Programming Fundamentals I
ACS-1903 Programming Fundamentals I
no prereq
Course class:
import java.util.*;
public class Course
{
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
}
PreReq class:
import java.util.*;
import java.io.*;
public class Prereqs
{
public static void main (String [] args){
Scanner kb = new Scanner (System.in);
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
System.out.println("Enter course number with the format: AAA-999");
String input = kb.next();
validate(input);
}
public static void course(Course nineteen04, Course nineteen03,Course two47, Course three47, Course two09, Course three09, String input ){
Course c1 = nineteen04.getPreReq();
Course c2 = two47.getPreReq();
Course c3 = three47.getPreReq();
Course c4 = two09.getPreReq();
Course c5 = three09.getPreReq();
switch (input){
case "ACS-1904":
System.out.println(nineteen04.getCourseName()+" "+nineteen04.getCourseNumber());
System.out.println("preReq: " + c1.getCourseName()+ " "+ c1.getCourseNumber());
}
}
public static String validate (String input)
{
String arg = input;
boolean valid = arg.length()==7;
if (!valid){
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
valid = arg.charAt(3) == '-';
if(!valid) {
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
for(int i=0; i < 3 && valid; i++){
valid = ((i == 3 && Character.isLetter(arg.charAt(i))));
}
for(int i=3; i < 3 && valid; i++){
valid = ((i==6 && Character.isDigit(arg.charAt(i))));
}
return arg;
}
}
A recursive method needs to contain a condition which terminates the recursion. Your list of courses and their prerequisites remind me of a linked list where each course points to its prerequisite. The list terminates when we reach a course that has no prerequisite. The below code is your Course class with the addition of a main method (imported from your Prereqs class) and the recursive method which I named requirements(). I also added method toString() to make the display of the list of courses and their prerequisites more "human readable". You can experiment by changing the course passed to the initial invocation of method requirements().
public class Course {
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
public String toString() {
return courseNumber + " " + courseName;
}
private static void requirements(Course c) {
if (c == null) {
return;
}
else {
System.out.println(c);
requirements(c.getPreReq());
}
}
public static void main(String[] args) {
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
requirements(three09);
}
}
Running the above code displays the following:
ACS-3909 Advanced Internet Programming
ACS-1903 Programming Fundamentals I
I am creating a program in Java for a restaurant. I am using ArrayList but for some reason my starter class doesn't seem to run in the main menu.
This is my starter class:
import java.util.ArrayList;
public class Starter
{
Starter()
{
String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
//System.out.println(myList[]);
}
}
This seems to be correct, but when I try to choose from the Main menu it doesn't seem to work.
Main Menu:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a =input.nextInt();
input.nextLine();
if(a==1)
{
System.out.println("Starter");
Starter OS1=new Starter();
System.out.println("Your starter is "+OS1.myList[]);
}
else if(a==2)
{
System.out.println("Main Course");
MaiinCourse OMC1=new MaiinCourse();
System.out.println("Your MainCourse is "+OMC1.MCname);
System.out.println("The price is "+OMC1.MCprice);
}
else if(a==3)
{
System.out.println("Desert");
Deserrt ODS1=new Deserrt();
System.out.println("Your Desert is "+ODS1.DSname);
System.out.println("The price is "+ODS1.DSprice);
}
else
{
System.out.println("End");
System.out.println("Program Closing");
System.exit(1);
}
}
}
The error I get is:
'.class' expected System.out.println("Your starter is "+OS1.myList[]);
How to fix this?
When I run the main menu it should allow me to choose from the array list.
I did few changes to your code. Now it works. Try and see.
import java.util.Arrays;
import java.util.Scanner;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1)
{
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println("Your starter is " + Arrays.toString(OS1.getMyList()));
}
}
}
class Starter
{
private String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
public String[] getMyList()
{
return myList;
}
}
Your code won't work because you are trying to give an Array values within you class constructor (Starter constructor in this case). This will lead to a RunTime exception because you cannot create Array constants within a constructor. I much more viable approach would be to create a private Array as an attribute for each object that you create of type "Starter". Then you can use something that we call a "Getter" method to get the value of the myList attribute for the instance you're creating. Here's a mini example of how we can change your Starter class structure below:
public class Starter {
private String[] myList = {"Coffee", "Tea", "Somola", "Cake"};
public String[] getterMethod() {
return this.myList;
}
}
Now we have what is called a "Getter" method in Java which will return the private class attribute so that users cannot alter the internal state of the Object. Here is an example of how you will call the Array in your main method:
public class App {
public static void main( String[] args ) throws IOException{
System.out.println("1=Starter");
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int a = input.nextInt();
if(a == 1) {
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println(Arrays.toString(OS1.getterMethod()));
}
}
}
That is a very simplified version of your code that I simply used to illustrate the broader concept. Here is the output:
1=Starter
Enter a number
1
Starter
[Coffee, Tea, Somola, Cake]
We simply call the getterMethod() which will return the value for the private Array that you are looking for.
Actually, your myArray is not visible outside the Starter class, so you have to make it visible by declaring as public, or package default. Here you can take help of Arraylist.
So you can change your class as below :
public class Starter {
// this myList will be visible outside of this class and can be accessed to show menu.
ArrayList<String> myList = new ArrayList<>();
Starter() {
String[] myArray = { "Coffee", "Tea", "Somosas", "Cake" };
for (String str : myArray) {
myList.add(str);
}
//System.out.println(myList);
}
}
and kindly update Your Menu.java class as below :
import java.util.Scanner;
public class Menu {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1) {
System.out.println("Starter : ");
Starter os1 = new Starter();
for (String str : os1.myList) {
System.out.print(str + " ");
}
}
}
}
This question already has answers here:
What is the difference between a member variable and a local variable?
(7 answers)
Closed 4 years ago.
I've already looked at all of the other stackoverflow questions on accessing an instance of an object from the main method and nothing I've tried has worked, I still continue to get the following error message
java.59: error: cannot find symbol
System.out.println(student2.getStudentId());
here is my main method trimmed down:
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class Testing {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "c:\\Users\\XXXXXX\\Documents\\Input01.txt";
Scanner br = new Scanner(new File(INPUT_FILE));
// Test 2 - Test first and second line of information from input file
String[] strArray;
while (br.hasNext()) {
strArray = br.nextLine().split(",");
if(strArray[0].equals("STUDENT")) {
processStudentData(strArray);
System.out.println(student2.getStudentId());
}
else
if(strArray[0].equals("GRADE ITEM")) {
processGradeItemData(strArray);
}
}
} //end main
// ***************************************************************
// Uses string array from input file to create new student object
public static void processStudentData(String[] a) {
System.out.println("Running Test 2a:");
if (a[1].equals("ADD")) {
Student student2 = new Student(a[2], a[3], a[4], a[5]);
}
} // End processStudentData
} //end Testing
here is my Student class trimmed down:
public class Student {
private String studentId; // Unique ID for each Student
private String studentFirstName; // Student's legal first name
private String studentLastName; // Student's legal last name
private String studentEmail; // Student's school email address
//************************************************************************
Student() {
} // end Student
//************************************************************************
public Student(String studentId, String studentFirstName, String studentLastName,
String studentEmail) {
if (studentId.equals("")) {
throw new IllegalArgumentException("Student ID cannot be blank.");
}
if (studentFirstName.equals("")) {
throw new IllegalArgumentException("Student first name cannot be blank.");
}
if (studentLastName.equals("")) {
throw new IllegalArgumentException("Student last name cannot be blank.");
}
if (studentEmail.equals("")) {
throw new IllegalArgumentException("Student email cannot be blank.");
}
if (!studentEmail.contains("#")) {
throw new IllegalArgumentException("Student email must have '#'.");
}
this.studentId = studentId;
this.studentFirstName = studentFirstName;
this.studentLastName = studentLastName;
this.studentEmail = studentEmail;
} // end Student
//************************************************************************
public String getStudentId() {
return studentId;
} // end getStudentId
I need to be able to print out the student information using my get methods from the main method yet still instantiate the student2 object through the processStudentData method. I do not want to have to change my get method to static as there will be multiple instances.
Any help would be greatly appreciated.
UPDATE: I've added in a return to the processStudentData method and am still recieving the same error as before (main method has not changed, processStudentData method updated below):
public static Student processStudentData(String[] a){
System.out.println("Running Test 2a:");
if (a[1].equals("ADD")) {
Student student2 = new Student(a[2], a[3], a[4], a[5]);
return student2;
}
return null;
}
Since student2 is defined as a local variable within the if statement of the processStudentData, it can only be used within that context (to which it is defined)
// Uses string array from input file to create new student object
public static void processStudentData(String[] a) {
System.out.println("Running Test 2a:");
if (a[1].equals("ADD")) {
Student student2 = new Student(a[2], a[3], a[4], a[5]);
}
} // End processStudentData
"A" solution would be to return the result to the caller...
// Uses string array from input file to create new student object
public static Student processStudentData(String[] a) {
System.out.println("Running Test 2a:");
if (a[1].equals("ADD")) {
return new Student(a[2], a[3], a[4], a[5]);
}
return null;
} // End processStudentData
Then you could use it something like...
Student student = processStudentData(strArray);
if (student != null) {
System.out.println(student.getStudentId());
}
You might want to take a closer look at:
Language Basics/Variables
Returning a Value from a Method
for more details
Try to do something like:
public static Student processStudentData(String[] a) {
System.out.println("Running Test 2a:");
if (a[1].equals("ADD")) {
Student student2 = new Student(a[2], a[3], a[4], a[5]);
return student2;
}
return null;
}
and don't forget to handle the NullPointerException.
import java.util.Scanner;
public class product
{
int productId[];
String productName,productType[];
float productPrice[];
public static void main(String...args)
{
shop ob=new shop();
ob.startshop();
}
}
class shop
{
product obj;
void startshop()
{
obj=new product();
obj.productId()={1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};
obj.productName={"Cadbury","Parker Vector","Nescafe","kissan jam","Herbal oil","Garnier man's","Lays chips","Bourn bourn biscuits","Bournvita","Pepse"};
obj.productType={"Chocolate","Stationary","Coffee","Jam","Oil","Face wash","chips","Biscuits","Health Supplement","Cold Drink"}
obj.productPrice={20,150,80,65,30,79,10,20,140,24};
Scanner oj=new Scanner(System.in);
System.out.println(obj.productName);
boolean c=true;
while(c==true)
{
System.out.println("Please press\n1 for view all products\n2 for view product detail\n3 to exit shop");
int ch=oj.nextInt();
switch(ch)
{
case 1:viewAllProducts();
break;
case 2:System.out.println("Enter product id to search starting from 1001 to 1010");
int i=oj.nextInt();
viewProductDetail(i);
break;
case 3:System.out.println("You are out of shop :)");
c=false;
break;
}
}
}
void viewAllProducts()
{ System.out.println("ID\t\tNAME\t\tTYPE\t\tPRICE");
for(int i=0;i<10;i++)
{
System.out.println(obj.prductId[i]+"\t\t"+obj.productName[i]+"\t\t+"+obj.product Type[i]+"\t\t"+obj.productPrice[i]);
}
}
void viewProductDetail(int id)
{
int k=15;
for(int i=0;i<10;i++)
{
if(obj.productId[i]==id)
k=i;
}
if(k<10)
{
System.out.println("Product id "+obj.productId[k]);
System.out.println("Product name "+obj.productName[k]);
System.out.println("Product type "+obj.productType[k]);
System.out.println("Product price "obj.productPrice[k]);
}
}
}
In this code due to following lines the code is giving error
obj.productId()={1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};
obj.productName={"Cadbury","Parker Vector","Nescafe","kissan
jam","Herbal oil","Garnier man's","Lays chips","Bourn bourn
biscuits","Bournvita","Pepse"};
obj.productType={"Chocolate","Stationary","Coffee","Jam","Oil","Face
wash","chips","Biscuits","Health Supplement","Cold Drink"};
obj.productPrice={20,150,80,65,30,79,10,20,140,24};
Please tell me if i am using a wrong syntax to initialize the instance variable of other class.
yes you are using a wrong syntax here. obj.productId() would be a function but in your case it is a parameter of the class Product Just write obj.productId.
But you have to keep in mind, that you can not use int array[] = {example} syntax after you created the parameter. You have to use this when u initialize your parameter.
You can do
float productPrice[] = {"0.0","1,1","2.2"};
but not
float productPrice[];
productPrice = {"0.0","1,1","2.2"};
I hope this will help you :)
obj.productId()={1001,1002,1003,1004,1005,1006,1007,1008,1009,1010}; This syntax is wrong, productId is not a function, use it without the brackets.
Example -
obj.productId= new int[]{1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};
I have modified your Question in the following way and I am getting the expected results. Please go through.
package product;
/**
*
* #author sunil
*/
import java.util.*;
public class product
{
int productId[];
String productName[],productType[];
int productPrice[];
public static void main(String args [])
{
shop ob = new shop();
ob.startshop();
}
}
class shop{
product obj;
void startshop()
{
obj = new product();
obj.productId = new int[]
{1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};
obj.productName= new String[]{"Cadbury","Parker Vector","Nescafe","kissan
jam","Herbal oil","Garnier man's","Lays chips","Bourn bourn
biscuits","Bournvita","Pepsi"};
obj.productType = new String[]
{"Chocolate","Stationary","Coffee","Jam","Oil","Face
wash","chips","Biscuits","Health Supplement","Cold Drink"};
obj.productPrice = new int[]{20,150,80,65,30,79,10,20,140,24};
Scanner oj=new Scanner(System.in);
System.out.println(Arrays.toString(obj.productId));
System.out.println(Arrays.toString(obj.productName));
System.out.println(Arrays.toString(obj.productType));
System.out.println(Arrays.toString(obj.productPrice));
boolean c=true;
while(c==true)
{
System.out.println("Please press\n1 for view all products\n2 for
view product detail\n3 to exit shop");
int ch=oj.nextInt();
switch(ch)
{
case 1:viewAllProducts();
break;
case 2:System.out.println("Enter product id to search starting
from 1001 to 1010");
int i=oj.nextInt();
viewProductDetail(i);
break;
case 3:System.out.println("You are out of shop :)");
c=false;
break;
}
}
}
void viewAllProducts()
{ System.out.println("ID\t\tNAME\t\tTYPE\t\tPRICE");
for(int i=0;i<10;i++)
{
System.out.println(obj.productId[i]+"\t\t"+obj.productName[i]
+"\t\t+"+obj.productType[i]+"\t\t"+obj.productPrice[i]);
}
}
void viewProductDetail(int id)
{
int k=15;
for(int i=0;i<10;i++)
{
if(obj.productId[i]==id)
k=i;
}
if(k<10)
{
System.out.println("Product id "+obj.productId[k]);
System.out.println("Product name "+obj.productName[k]);
System.out.println("Product type "+obj.productType[k]);
System.out.println("Product price "+obj.productPrice[k]);
}
}
}
I am learning Java and so, I want easy and understandable answer.
You will know what I mean when you see the code below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser = new Playeri();
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Suppose input is: John.
Then, output will be:
Your name is John.
Hey, bro! Are you null?
Here, I want John instead of null in output(line 2).
But I can't.
How can I access the same input to other classes (for e.g: Enemyu) other then the class having the declararion of the variable in which input is set (for e.g: Playeri)?
In Other Words:
How can multiple classes access the same value of variable that is set in a class through main method?
Please answer my question!
Thank you very much!
EDIT: Sorry for incorrect indentation in the code.
You are not setting value to the object's name variable.
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
Enemyu.enemUser.name=name; // Set it like this
}
}
class Enemyu {
static Playeri enemUser = new Playeri(); // make it static
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Output -
John
Your name is John.
Hey, bro! Are you John?
This solves your problem, but It is recommended you use setter-getter method.
You can pass it as a parameter to that method.
void showName(String myName) {
System.out.println("Your name is " + myName + ".");
}
and
enem.showUserName(user.name);
or, you could set it the way you did with the user class.
or, you could use mutators (setters/getters) in this case, a set-method, or pass it as a parameter to the constructor of the class.
Here is a fixed version of your code. The problem that you had was that you created two separate instances of Playeri and only set the name on one of the instances. This solution only creates a single instance of Playeri, thus bypassing the problem.
import java.util.Scanner;
public class Foo {
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu(user);
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser;
public Enemyu( Playeri p ) {
this.enemUser = p;
}
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
In your Enemyu class create getters and setters for your field variables.
Inside Enemeyu...
private String name;
...
public void setName(String newName) {
this.name = newName;
}
public String getName() {
return this.name;
}
...
Then inside your main method...
...
Enemyu enem = new Enemyu();
enem.setName("John");
Granted you might also want to provide your class with an overidden toString() method (which in your case is your showName). However, in your case; I don't think that will be necessary.
Your problem was that you were never setting the name field in the object.