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);
}
}
Related
I'm pretty new to java and could not find a question answering my problem particulary.
I initialized an arraylist as instance variable and in one method I edit this arraylist which also works, but I'm having trouble storing this value in the instance variable and then reading it in a different method because then it appears empty again. I tried using getter and setter but that didn't really work even though I suppose that that is part of the solution...
Here some relevant snippets of my code:
public class CarManager {
ArrayList<Car> carList = new ArrayList<>();
String carId ="";
String driver= "";
int sizeCategory= 0;
Car myCar= new Car (carId,driver,sizeCategory);`
public void addCar () {
CarManager myCarManager= new CarManager();
Car car1 = new Car(carId,driver,sizeCategory);
carId= car1.getCarId(carId);
driver= car1.getDriver (driver);
sizeCategory= car1.getSizeCategory (sizeCategory);
System.out.println("You entered the following data:");
System.out.println("\ncar ID: "+ carId);
System.out.println("driver's name:" +driver);
System.out.println("size category: "+sizeCategory);
System.out.println("\nIf you are okay with this, press 0 to save the data and return to the CARS MENU");
System.out.println("\nIf you made a mistake, press 1 to enter the data again");
Scanner afterAddCar= new Scanner(System.in);
String choice1;
choice1= afterAddCar.next().trim();
if ("1".equals (choice1)) {
myCarManager.addCar();
}
if ("0".equals (choice1)) {
Car returnedCar= new Car (carId,driver,sizeCategory);
carList.add(returnedCar);
String list = carList.toString();
System.out.println(list);
myCarManager.setCarList(carList);
ArrayList<Car> afterAdd= carList;
myCarManager.handleCars();
}
}
public ArrayList<Car> getCarList() {
return carList;
}
public void setCarList(ArrayList<Car> carList) {
this.carList = carList;
}
public void listCars () {
String list = carList.toString();
System.out.println(list);
}
I have a second class called Car which I'll also post here for better understanding:
public class Car {
private String carId;
private String driver;
private int sizeCategory; // value from 1-3 indicating the size of the car
public Car () {}
public Car (String carId,String driver,int sizeCategory){
this.carId= carId;
this.driver= driver;
this.sizeCategory= sizeCategory;
}
public String getCarId(String carId) {
Scanner keyboard = new Scanner(System.in);
System.out.println("\nFirst enter the car ID: " + carId);
while (carId.length() < 6) {
System.out.println("Please enter an ID that has at least 6 characters");
carId = keyboard.next();
}
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public String getDriver(String driver) {
Scanner keyboard = new Scanner(System.in);
System.out.println("\nNext enter the driver's name:" + driver);
driver= driver.trim();
while (driver.length() < 2) {
System.out.println("Please enter a name that has at least 2 characters");
driver = keyboard.next();
driver= driver.trim();
}
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public int getSizeCategory(int sizeCategory) {
Scanner keyboard = new Scanner(System.in);
String input="";
System.out.println("\nNow the size category: ");
while (sizeCategory <1 || sizeCategory >3) {
System.out.println("The size category has to be between one and three");
input = keyboard.next().trim();
try {
sizeCategory = Integer.parseInt(input);
} catch (Exception e) {
sizeCategory = 0;
}
}
return sizeCategory;
}
public void setSizeCategory(int sizeCategory) {
this.sizeCategory = sizeCategory;
}
Now I know that there is probably more than one thing that could be improved here, but I'm mostly interested in solving the problem with the listing of the updated arraylist.
Thanks a lot in advance!
Your problem seems to be that you are creating a new CarManager everytime, and using recursive to go inside a new CarManager that you created in your addCar() method. it looks to me that you only need one CarManager and all the Car instances get added to your ArrayList<Car> that is a field in your Car Manager.
i assumed this because your Car class have fields :
private String carId;
private String driver;
private int sizeCategory;
and the same fields are being repeated in your CarManager for no use basically.
I suggest to use a while loop to check for user input, such as :
public void addCar(Scanner scanner) { // passing on the scanner
while (true) {
// ask the user for inputs
String carId = scanner.nextLine();
String driver = scanner.nextLine();
int sizeCatagory = Integer.parseInt(scanner.nextLine());
// ask user for confirmation
if (scanner.nextLine().equals("1") {
continue;
} else {
carList.add(new Car(carId,driver,sizeCategory));
break;
}
}
}
I'm still trying to make the text editor to run with cmd but I'm stuck.
import java.util.Scanner;
public class TextEd {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Editor editor = new Editor();
editor.copiedText();
}
}
class Editor {
Scanner scan = new Scanner(System.in);
public void copiedText() {
System.out.println("Paste your text here");
String text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters"?;
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
The problem is: everytime i try to execute i get an error "cannot find symbol 'text". I know I need to call it frim the other method, but hod do i do that?
Yoy need to make it a class field:
class Editor {
private Scanner scan = new Scanner(System.in);
private String text = "";
public void copiedText() {
System.out.println("Paste your text here");
text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters"?;
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
Also field scan in class TextEd seems to have no purpose and should therefore be removed.
You have declared text as a local variable in copiedText(). Local variables cannot be seen in other methods. Try setting a field variable (a private variable in the Editor class) that can be seen by all methods
your code has compile error because the parentheses in System.out.println() in menu are not closed properly.
you want to call a method of a text String in another method, so you can pass text to that method or just define it as a field in your class so that other methods can reach that variable.
import java.util.Scanner;
public class TextEd {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Editor editor = new Editor();
editor.copiedText();
}
}
class Editor {
Scanner scan = new Scanner(System.in);
String text;
public void copiedText() {
System.out.println("Paste your text here");
text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters?");
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
be aware of blocks, every variable that is defined in other blocks or methods, is not reachable in other blocks or methods.
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;
}
I am programming an TBAP (Texted base adventure program) just because. I just started it, and I am already having issues with it. What I want to do is have a main class that introduces the program, in output text. At the end of the class it asks "Where would you like to go on your adventures?" It has five options 3 of them are separate adventures of two of them are inventory classes. Right now I am stuck on the my first adventure class. I have an int variable called path. If path == 1, you go to fantasy island class go on your adventure. Is there any to call that adventure with an if statement? I made a constructor and getters and setters with my variables name and path.
Summerproject class:
package summerproject;
import java.util.Scanner;
import static summerproject.Fanastyisland.name;
import static summerproject.Fanastyisland.path;
public class Summerproject {
private static int path;
private static String name;
public Summerproject (int path, String name)
{
this.path = path;
this.name = name;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public int getPath() {
return path;
}
public void setPath(int path) {
this.path = path;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the adventure text program! You are the choosen one to save the universe");
System.out.println("Press any key to continue...");
try
{
System.in.read();
}
catch(Exception e)
{}
System.out.println("Welcome. You are the choose one, a legend,a becon of hope to save the universe from the forces of evil.");
System.out.println("Only with you skills and your great power can you destroy the evil doing world.");
System.out.println("Please enter heros name");
name = in.next();
System.out.println("Okay " + name + ", lets begin our adventure!!");
System.out.println("The world can be saved, there is hope. But in order to save the world, \n "
+ "+ you must complete 9 tasks in three diffrent places in three diffrent periods of time. The past, the present and the future.");
System.out.println("Press any key to continue...");
try
{
System.in.read();
}
catch(Exception e)
{}
System.out.println("The three places are the past in the year 1322 in Fantasy island");
System.out.println("The present is the evil little town of Keene N.H.");
System.out.println("And the future to the year 2567 in Space!");
System.out.println("Where would you like to go on your adventures?");
System.out.println(" 1). Fantasy Island");
System.out.println(" 2). Keene");
System.out.println(" 3). Outer space");
System.out.println(" 4). Buy wepons or potions!");
System.out.println(" 5). Sell wepons!");
path = in.nextInt();
if (path == 1)
{
}
}
}
here is my fantasy island class:
package summerproject;
import java.util.Scanner;
import static summerproject.Fanastyisland.name;
import static summerproject.Fanastyisland.path;
public class Fanastyisland extends Summerproject {
public static String name;
public static int path;
public Fanastyisland (String name, int path)
{
super(path,name);
name = name;
path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPath() {
return path;
}
public void setPath(int Path) {
this.path = path;
}
public static void main(String[] args)
//this is where the fantasy island adventure begins.
{
System.out.println("Welcome to fantasy island!!")
}
}
Like I said, I want to call the sub classes with an if statement and I don't know how to do that. If I type in one 1, I want to go to the fantasy island class. I haven't programmed the adventure yet, I will get to it once it is fixed, I just want the output for now to be "Welcome to fantasy island!" when I type 1. Any help would be great! Thank you!
Something like this:
Summerproject adventure = null;
switch (path) {
case 1:
adventure = new FantasyIsland (...);
break;
case 2:
adventure = new Keene (...);
break;
...
default:
System.out.println ("Illegal choice(" & path & "): try again");
}
if (adventure != null) {
adventure.play ();
...
You could just create a common interface
public interface Adventures{
public void start();
}
Every adventure could implement this interface and override the start method
public class AdventureA implements Adventures {
#Override
public void start() {
// Do whatever you want
}
}
You summerproject could simply have a class variable with the type of the interface.
public class Summerproject {
private static int path;
private static String name;
private Adventure adventure;
...
}
Afterwards in the if statements you could just assign this adventure and call the start method.
if (path == 1)
{
adventure = new AdventureA();
adventure.start();
}
So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {