I apologize for the lengthy submission but I am having some difficulty with getting this program to work correctly.
There is another Driver program that runs this one and it requires me to print out the name, level, supplies, etc., of a Magician (given certain parameters).
However, when I use the toString() method to print out the String. I continuously get a
"null" response for my name/level/supplies. My numbers also seem to not update.
Could someone take a look and see what I am doing wrong?
I just can't seem to make the program pick up the Magician parameters.
public class Magician
{
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String initialValues)
{
double health = 1000;
int galleons = 200;
initialValues = name + "#" + level + "#" + supplies;
}
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
}
This is the beginning of the Driver program that I can not get to print out:
public class MagicAndMalice
{
public static void main (String[] args)
{
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
System.out.println(harry); // test toString() method
System.out.println("------------------------\n\n");
}
}
First, you are declaring health and galleons again. You should not declare them again, just assign the values:
health = 1000;
galleons = 200;
Also, it seems like you are confused about assignment. If you want to assign some value to name, level and supplies, you have to do:
name = ...;
level = ...;
supplies = ...;
If initialValues will contain a string like "a#b#c" and you want to assign each "part" to those variables, you can use String#split():
String[] parts = initialValues.split("#");
name = parts[0];
level = parts[1];
supplies = parts[2];
But I would really recommend you to read a book or follow some tutorials of Java, so you get the basics first.
You are missunderstanding the value assignment thing in Java. You won't need a separator like #, but if you do, you would need to e.g. substr the given String in the constructor.
Here's a short (untested) version, that should clarify what I mean:
public class Magician {
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String name, String level, String supplies) {
health = 1000;
galleons = 200;
this.name = name;
this.level = level;
this.supplies = supplies;
}
// Let's do some Constructor overloading here
public Magician(String initialValueString) {
String[] initialValues = initialValueString.split("#");
this(initialValues[0], initialValues[1], initialValues[2]);
}
public String toString() {
return "Name: " + name +
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " + supplies;
}
}
public class MagicAndMalice {
public static void main (String[] args) {
// Method one
Magician harry = new Magician("Harry Potter", "apprentice", "Wand");
System.out.println(harry);
System.out.println("------------------------\n\n");
// Method two
Magician ron = new Magician("Ron Weasley#apprentice#Owl");
System.out.println(ron);
System.out.println("------------------------\n\n");
}
}
And if you want to have more values than just one in the supplies field, have a look at Array or try to split/substr the values with some regular expressions.
Hope that helped to get some clearer about the variable assignment in Java.
When you create object as
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
only double health = 1000; & int galleons = 200; get initialled as some value.
When you call toString() method then
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
the value null for some field is returned because it is not initialized at all.
I think it might make more sense to change your constructor to take separate arguments instead of one string that has to be split up.
public Magician(String name, String levels, String supplies, int gallons, double health) {
this.name = name;
this.levels = levels;
...
}
Notice the prefix "this." which prevents name conflicts between the member variables of the class and the parameters passed to the constructor.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
New here, so please go easy on me! I've searched other articles on the subject but can't quite find the answer i'm looking for. Hoping someone can help.
Two separate classes, object class and main method. I need to print the object details using toString, but I can't work out how to print the toppings, which are being passed as an array from the main method. The code runs ok, but when I call getToppings() from the toString method, it just prints the id of the array object name, rather than the contents of the array itself.
Can anyone help?
Thanks in advance,
Marc
package toString;
/*
* class to represent a pizza object.
*/
public class Pizza
{
private String name;
private String [] toppings;
private double price;
public Pizza(String reqName, String [] reqToppings, double reqPrice)
{
name = reqName;
toppings = reqToppings;
price = reqPrice;
}
public String getName()
{
return name;
}
public String[] getToppings()
{
return toppings;
}
public double getPrice()
{
return price;
}
public String toString()
{
return "The pizza name is " + getName() + ", the toppings are " + getToppings() + " and the price is £" + getPrice();
}
}
package toString;
public class TestPizza
{
public static void main(String[] args)
{
String[] pepperoni = {"Pepperoni", "minced beef"};
String[] diavalo = {"Pepperoni", "minced beef", "chillies"};
String[] chicken = {"Chicken", "sweetcorn"};
Pizza [] pizzaList = new Pizza[3];
pizzaList[0] = new Pizza("Pepperoni", pepperoni, 6.95);
pizzaList[1] = new Pizza("Diavalo", diavalo, 7.95);
pizzaList[2] = new Pizza("Chicken & Sweetcorn", chicken, 8.95);
System.out.println(pizzaList[0].toString());
System.out.println(pizzaList[1].toString());
System.out.println(pizzaList[2].toString());
}
}
You have to go through array and print out every item:
public String toString(){
String s = "The pizza name is " + getName() + ", the toppings are: ";
for(int i = 0; i<getToppings().size; i++){
s += getToppings[i] + ", ";
}
s += "and the price is £" + getPrice();
return s;
}
In my Main class I have this piece of code:
UUID uniqueID;
public void createEmployee(){
uniqueID = UUID.randomUUID();
// ...
}
In my class Corporation there's a method called promoteEmployee, which should receive the uniqueID as parameter. Is that possible, and when yes, how?
public void promoteEmployee(uniqueID){
// it doesn't recognize uniqueID as argument
}
I also have the method sortEmployees, which sorts the ArrayList alphabetically, and if two names are equal, the employee with a higher salary should be printed out first. It sorts the List alphabetically, but doesn't check if the salary is bigger. What do I need to change?
ArrayList<Employee> employees = new ArrayList<Employee>();
public void sortEmployees(){
Collections.sort(employees, (p1, p2) -> p1.name.compareTo(p2.name));
for(Employee employee: employees){
Comparator.comparing(object -> employee.name).thenComparingDouble(object -> employee.grossSalary);
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: "+employee.name + END_OF_LINE + "Salary: " + employee.grossSalary);
System.out.println(""); // just an empty line
}
}
Change the method to be valid java code
public void promoteEmployee(UUID uniqueID){
but as it even seems to be a field, why pass the value at all?
As for sorting see
Implementing Java Comparator
one passes variables from one class to another's methods by using the classname.method(arg) syntax.
public class JavaTeachMe2018
{
//variable in other class to be passed as a method argument
public static int startID = 0;
public static void main(String[] args)
{
// we are passing startID to anouther class's method
String[] currentEmployees = Corporation.createEmployee(startID);
System.out.println("Welcome " + currentEmployees[1] + " to the company as employee number " + currentEmployees[0]);
}
}// end class teachme
here is the second class
import java.util.Scanner;
public class Corporation
{
public static int createId(int startID)
{
// create unique id
int uniqueID = startID + 1;
return uniqueID;
}
public static String[] createEmployee(int startID)
{
// assign a variable to the return of the createId call
int employeeNumber = createId(startID);
System.out.println("Your assigned employee number is " + employeeNumber);
// get employee name
Scanner stdin = new Scanner(System.in);
System.out.print(" Enter Your Name : ");
String employeeName = stdin.nextLine();
String employees[] = {Integer.toString(employeeNumber), employeeName};
return employees;
}
}
In this code I am making a Bank Account of sorts. It has a basic BankAccount that has variables Name and id. It has a savings account that has interest and a checking account with a credit line. Both of those classes extends to the BankAccountInfo class.
In the Teller class I have a constructor Teller with a name and date processed that is set in the Main(). I have a method called setUpAccts() that includes the accounts I have created so far, the checking, savings and two basic bankaccounts.
In the Main() I want to be be able to have multiple tellers calling specific accounts.
For example, I want Teller John to only call acct1, which would be the checking account. Then I want another teller, Kate, to only call acct2, the savings account and it's content.
As it stands I only have a single Teller calling every single account in the setUpAccts() method.
Here is the Teller code.
EDIT: Sorry for having a horrible description, I hope the new one makes my problem more clear.
class Teller
{
String name;
String dateProcessed;
int random;
public Teller(String n, String dP)
{
name = n;
dateProcessed = dP;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
public void setUpAccts()
{
CheckingAccount acct1 = new CheckingAccount("Dylan Kuchar", 11, "Checking");
//acct1.setCheckingAccount("Dylan", "11", "Checking", acct1.getOverdraft());
acct1.printCheckingAccount();
acct1.setBalance(250);
//acct1.printBalance();
acct1.withdraw(120.5);
//acct1.printBalance();
SavingsAccount acct2 = new SavingsAccount("Emily Doe", 2, "Savings");
acct2.printSavingsAccount();
acct2.setBalance(225.5);
acct2.InterestBalance();
acct2.withdraw(500);
BankAccountInfo acct3 = new BankAccountInfo();
acct3.BankAccountInfo("Dylan", 11);
acct3.printBankAccountInfo();
acct3.setBalance(150);
acct3.deposit(20);
acct3.printBalance();
BankAccountInfo acct4 = new BankAccountInfo();
acct4.BankAccountInfo("Emily", 2);
acct4.printBankAccountInfo();
acct4.setBalance(650);
acct4.withdraw(150);
acct4.printBalance();
}
public static void main(String args[])
{
Teller t = new Teller("John", "Today");
t.setUpAccts();
}
}
Well, the simple way is simply making a teller a specific type on initialization. So your code would change to:
class Teller
{
String name;
String dateProcessed;
Boolean Savings;
int random;
public Teller(String n, String dP, Boolean Savings)
{
name = n;
dateProcessed = dP;
this.Savings = Savings;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
then you just change your setUpAccts class to only deal with one Person. and place a if else to see if the teller is dealing with savings or checking. prolly not the best, but its what came to mind.
Edit:
What you can do is create a Class called Account, CheckingAccount and Savings Account would inherit from this class. You can then do this:
class Teller
{
Account acct;
String name;
String dateProcessed;
int random;
public Teller(Account act, String dP)
{
acct=act;
name = acct.getname();
dateProcessed = dP;
System.out.println("Teller:" + " " + name + " " + "This transaction will process:" + " " + dateProcessed);
}
public void acctStuff()
{
if(acct instenceof checkingAccount)
{ //do checking stuff}
else { //do savings stuff}
}
let me know if I missed something or if something doesnt make sense
Hi guys I'm currently creating a program that allows the user to create an array, search an array and delete an element from an array. Looking at the LibraryMenu method, the first case where you create an array in the switch statement works fine, however the other ones create a "cannot find symbol error" when I try to compile.
My question is I want the search and delete functions to refer to the first switch case - the create Library array. Any help is appreciated, even if its likely from a simple mistake.
import java.util.*;
public class EnterLibrary
{
public static void LibraryMenu()
{
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
LibraryMenu Menu = new LibraryMenu();
Menu.displayMenu();
switch (scannerObject.nextInt() )
{
case '1':
{
System.out.println ("1 - Add Videos");
Library[] newLibrary;
newLibrary = createLibrary();
}
break;
case '2':
System.out.println ("2 - Search Videos");
searchLibrary(newLibrary);
break;
case '3':
{
System.out.println ("3 - Change Videos");
//Change video method TBA
}
break;
case '4':
System.out.println ("4 - Delete Videos");
deleteVideo(newLibrary);
break;
default:
System.out.println ("Unrecognized option - please select options 1-3 ");
break;
}
}
public static Library[] createLibrary()
{
Library[] videos = new Library[4];
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int i = 0; i < videos.length; i++)
{
//User enters values into set methods in Library class
System.out.print("Enter video number: " + (i+1) + "\n");
String number = scannerObject.nextLine();
System.out.print("Enter video title: " + (i+1) + "\n");
String title = scannerObject.nextLine();
System.out.print("Enter video publisher: " + (i+1) + "\n");
String publisher = scannerObject.nextLine();
System.out.print("Enter video duration: " + (i+1) + "\n");
String duration = scannerObject.nextLine();
System.out.print("Enter video date: " + (i+1) + "\n");
String date= scannerObject.nextLine();
System.out.print("VIDEO " + (i+1) + " ENTRY ADDED " + "\n \n");
//Initialize arrays
videos[i] = new Library ();
videos[i].setVideo( number, title, publisher, duration, date );
}
return videos;
}
public static void printVidLibrary( Library[] videos)
{
//Get methods to print results
System.out.print("\n======VIDEO CATALOGUE====== \n");
for (int i = 0; i < videos.length; i++)
{
System.out.print("Video number " + (i+1) + ": \n" + videos[i].getNumber() + "\n ");
System.out.print("Video title " + (i+1) + ": \n" + videos[i].getTitle() + "\n ");
System.out.print("Video publisher " + (i+1) + ": \n" + videos[i].getPublisher() + "\n ");
System.out.print("Video duration " + (i+1) + ": \n" + videos[i].getDuration() + "\n ");
System.out.print("Video date " + (i+1) + ": \n" + videos[i].getDate() + "\n ");
}
}
public static Library searchLibrary( Library[] videos)
{
//User enters values to setSearch
Library titleResult = new Library();
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int n = 0; n < videos.length; n++)
{
System.out.println("Search for video number:\n");
String newSearch = scannerObject.nextLine();
titleResult.getSearch( videos, newSearch);
if (!titleResult.equals(-1))
{
System.out.print("Match found!\n" + newSearch + "\n");
}
else if (titleResult.equals(-1))
{
System.out.print("Sorry, no matches found!\n");
}
}
return titleResult;
}
public static void deleteVideo( Library[] videos)
{
Library titleResult = new Library();
java.util.Scanner scannerObject =new java.util.Scanner(System.in);
for (int n = 0; n < videos.length; n++)
{
System.out.println("Search for video number:\n");
String deleteSearch = scannerObject.nextLine();
titleResult.deleteVideo(videos, deleteSearch);
System.out.print("Video deleted\n");
}
}
public static void main(String[] args)
{
Library[] newLibrary;
new LibraryMenu();
}
}
I think this is a terrible design. You've mingled too many things together: user interface, logic, data structure.
Start by isolating your LibraryArray from the LibraryMenu. You shouldn't see any switch or input or output in it at all.
Java's an object-oriented language. Start thinking about your system in terms of objects. I don't see classes like Video and VideoCatalog. You'll find this system to be a lot easier to implement if you created them.
Looks like you've got a start:
package model;
public class Video {
private Long id;
private String title;
private String publisher;
private int durationSeconds;
private Date publicationDate;
// add ctors, getters, etc. Immutable? Could be...
// equals, hash code, toString
}
Keep your VideoCatalog free of user interface or I/O:
package model;
public interface VideoCatalog {
List<Video> find();
List<Video> find(String title);
List<Video> find(Date startDate, Date endDate) ;
Long save(Video video);
void update(Video video);
void delete(Video video);
}
Now you can have an implementation that uses any data structure you want:
package model;
public class VideoCatalogImpl implements VideoCatalog {
private Set<Video> videos;
// add implementations here.
}
You need to move the declaration of that array variable out of the scope of the first case, and up to someplace where the other cases can see it. Given the current structure of your code, it would be most convenient to make it a static member of the class -- i.e.,
public class EnterLibrary
{
Library[] newLibrary;
Then all the static methods of this class could share the one variable. But be sure to remove all the other declarations of the variable that appear in other methods, otherwise they still will be using separate variables, and bugs like that can be very hard to track down!
Library[] newLibrary; is defined in your case '1' only, you should define it in a wider scope, like your LibraryMenu method. Also, the Library[] newLibrary declared in your main is not called anywhere, and maybe you should add Null check in your search, print an delete methods.
Your constructor class must have the same name of your class and not have any modifier keywords in it. Also, when you create an object of your class, it wont use the static methods declared in there.
A note: when you work with your own declared arrays, it would be better that you declare a int variable to keep track of the actual size of the array. Note that array.length returns how many items the array can have, not how many items it already has.
I would redesign your definitions (not the code) to something like this:
//Note I changed the classname from EnterLibrary to LibraryMenu. Apparently you
//wanted a LibraryMenu class.
public class LibraryMenu {
private final int MAX_ITEMS = 50;
private Library[] videos;
private int size = 0;
//remove the static and void keyworkds from this method, so this will be
//the constructor.
public LibraryMenu() {
videos = new Library[MAX_ITEMS];
//the rest of your code here...
switch (scannerObject.nextInt()) {
//if you're reading an int, keep the constants in the case as int.
case 1:
//no need of brackets inside a case statement
//check that you can add an item in your Library array
//also, its not good to ask the user to add 4 (or N) videos in 1 round :).
if (size < MAX_ITEMS) {
Library video = addVideo();
videos[size++] = video;
}
break;
case 2:
break;
}
}
//remove the static keyword so the instance of your class can call the method.
public Library addVideo() {
Library video = new Library();
//your code to read data goes here...
//then fulfill the video and return it.
return video;
}
//The Library[] videos is declared in your class, so all other methods could
//use it without having to receive it as a parameter.
public void printVidLibrary() {
//your code goes here...
}
public Library searchLibrary() {
//your code goes here...
}
public void deleteVideo( Library[] videos) {
//your code goes here...
}
public static void main(String[] args) {
new LibraryMenu();
}
}
Try this,
Declare Library[] newLibrary; as an instance variable (at class scope), or as local variable before the switch statement.
This is my Code that I have so far:
import java.util.*;
public class VoteRecorder
{
// Variables and instance variables
public static String nameCandidatePresident1;
public static String nameCandidatePresident2;
public static String nameCandidateVicePresident1;
public static String nameCandidateVicePresident2;
public static int votesCandidatePresident1;
public static int votesCandidatePresident2;
public static int votesCandidateVicePresident1;
public static int votesCandidateVicePresident2;
private int myVoteForPresident;
private int myVoteForVicePresident;
public VoteRecorder()
{
nameCandidatePresident1 = "null";
nameCandidatePresident2 = "null";
nameCandidateVicePresident1 = "null";
nameCandidateVicePresident2 = "null";
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
myVoteForPresident = 0;
myVoteForVicePresident = 0;
}
public void setCandidatesPresident(String name1, String name2)
{
nameCandidatePresident1 = name1;
nameCandidatePresident2 = name2;
}
public void setCandidatesVicePresident(String name1, String name2)
{
nameCandidateVicePresident1 = name1;
nameCandidateVicePresident2 = name2;
}
public static void resetVotes()
{
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
}
public static String getCurrentVotePresident()
{
return nameCandidatePresident1 + ":" + votesCandidatePresident1 + "\n" +
nameCandidatePresident2 + ":" + votesCandidatePresident2;
}
public static String getCurrentVoteVicePresident()
{
return nameCandidateVicePresident1 + ":" + votesCandidateVicePresident1 + "\n" +
nameCandidateVicePresident2 + ":" + votesCandidateVicePresident2;
}
public void getAndConfirmVotes()
{
}
private String getVotes()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("please vote for a President or vice president " + nameCandidatePresident1 + ", " + nameCandidatePresident2 + ", " + nameCandidateVicePresident1
+ " or " + nameCandidateVicePresident2);
String presidentVote = keyboard.nextLine();
if (presidentVote.equalsIgnoreCase(nameCandidatePresident1))
return nameCandidatePresident1;
if(presidentVote.equalsIgnoreCase(nameCandidatePresident2))
return nameCandidatePresident1;
System.out.println("please vote for a Vice president " + nameCandidateVicePresident1 + " or" + nameCandidateVicePresident2);
String vicePresidentVote = keyboard.nextLine();
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident1))
return nameCandidateVicePresident1;
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident2))
return nameCandidateVicePresident2;
else
return "not a valid vote";
}
private boolean confirmVotes()
{
System.out.println("Your vote for President is:");
System.out.println("your vote for Vice President is:");
System.out.println("Is this correct? Yes or No?");
Scanner keyboard = new Scanner(System.in);
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes"))
return true;
else
return false;
}
private void recordVote()
{
puscode: If confirmVotes returns true, take the nameCandidate, and ++ to votesCandidate of the same type
Copy this If statement four times, one for each of the candidates, 2 president and 2 vp.
Else or If confirmvotes returns false, put output saying that the votes were not confirmed.
}
}
Say i had all this code, lets look at the method getVotes() and confrimVotes(), in getVotes() the user picks a candidate and than that candidate is returned. How would i get that return statement to show up else where in other methods? like in confirmVote() i want to do this
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
But how can i do that?
This is not a direct answer to your question, but I think your code could be made a lot simpler by harnessing some of the power of object-oriented programming.
You are storing multiple types of information about 4 candidates for different positions as separate variables, and it's making your class very unwieldy.
A (in my opinion) better approach would be to have e.g. a Candidate class to store information about a single candidate, and then your classes could look as follows:
class Candidate {
String Name;
int votes;
}
class VoteRecorder {
Candidate[] presidents;
Candidate[] vicePresidents;
Candidate myVoteForPresident; //Or even make these both ints.
Candidate myVoteForVicePresident;
}
The classes can be further refined, but this will be a start. Any time you see multiple pieces of information that describe the same entity being repeated multiple times, it's a good indication that you could simplify your life by adding a class to represent them together instead.
Edit (to answer question specifically):
If you want to do effectively the following:
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
You can write something like this:
String voteResult = getVotes();
System.out.println("Your vote for President is: " + voteResult);
Or in one line:
System.out.println("Your vote for President is: " + getVotes());
Each time you run this code though, it will prompt the user for input. If you want to save the result until next time as well, you will have to save it to an attribute, e.g. by having a string in your class, and assigning the value to it first. Then just use that later instead of the local variable voteResult.