so I am currently taking an online coding class. and it has us make two different codes. one called SpaService. and one called CreateSpaService.
From my understanding, these are supposed to work together, to call variable (etc.) but it is not working and I am being hit with syntax errors saying that variables are not declared, but I declared them in the other code.
Am I supposed to put them in the same doc or something? I tried that and it still wouldn't work. Is there some way I have to link the two codes so they work together?
Here are the two codes.
also, do you see any syntax errors?
Thank you so much
import java.util.Scanner;
public class CreateSpaServices
{
public static void main(String[] args)
{
SpaService firstService = new SpaService();
SpaService secondService = new SpaService();
firstService = getData(firstService);
secondService = getData(secondService);
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() + " $" + firstService.getPrice());
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescrption() + " $" + secondService.getPrice());
}
public static SpaService getData(SpaService service)
{
String service;
double price;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
keyboard.nextLine();
service.setServiceDescription(Service);
service.setPrice(price);
return service;
}
}
//here is other code, im not sure if where I put this, or if I keep it in its own document or in this doc.
public class SpaService
{
private String serviceDescription;
private double price;
public SpaService()
{
serviceDescription = "XXX";
price = 0;
}
public void setServiceDescription(String service)
{
serviceDescription = service;
}
public void setPrice(double servicePrice)
{
price = servicePrice;
}
public String getServiceDescription;
{
return serviceDescription;
}
public double getPrice()
{
return price;
}
}
You want to have the two classes in respective files in the same folder location:
SpaService.java
CreateSpaServices.java
Are you using some kind of IDE or using command prompt to manually compile and execute? IDE make things very simple but they take away some finer learning details for beginners.
Anyway a text file can have one Public class and any number of non-public class. As your both classes are public it should be in different file. Classes are linked to each other via import statement , which must be first line in java class if any.
You should get some compile issues also as I can see this method
public static SpaService getData(SpaService service)
As you are returning service variable which is of type String, but your method signature is expecting SpaService
The other answers are useful for understanding the class structure, but you have an issue with your code issue that is likely causing the majority of your problem.
In the getData method you have two items named service, the SpaService service and String service;, you need to change one of them.
This line is not valid service.setServiceDescription(Service);, you can't refer to Service with a capital S, you need to reference to a valid string.
Here is an example that takes the above into account:
public static SpaService getData(SpaService service)
{
//Create a scanner
Scanner keyboard = new Scanner(System.in);
//Get scanner input
System.out.print("Enter service >> ");
String description = keyboard.nextLine();
//Add input to SpaService object
service.setServiceDescription(description);
//Get scanner input
System.out.print("Enter price >> ");
double price = keyboard.nextDouble();
//Add input to SpaService object
service.setPrice(price);
//Return SpaService object
return service;
}
For better help please edit your question to include the full error.
Related
I am trying to make this program That uses the scanner method. A user would type their name, then the ScannerToolclass would store that information into the guess string varible. An Object is created in the portation class as ScannerTool cool = new ScannerTool(); for both the justPoints() and post() methods. The portation class takes the objects and store what the user types into a String variable called hope as String hope = cool.scannerT() it then takes what the user types and executes an if statement. I create an object for the portation class and ScannerTool inside the MainTest and then I run it from MainTest class.
My problem is that when I run this program it throws an exception error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.justPoints(portation.java:12)
at MainTest.main(MainTest.java:20)
However, when i dont use the portation class and just go from ScannerTool to MainTest with the same code from portation it works. The weird part is that when I do it the original way there are no errors presented at the lines, only when I execute the whole program
What I tried: I tried to change the return types in the methods in portation from int and string to void, that didn't work. I tried looking at the lines that said where the error occured, but that didn't help becuase everything looked correct. Since it's not throwing actual errors on the IDE before running i'm at a loss.
the code:
The code that works:
MainTest
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
//portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
int points = 0; // taken from the portation class
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println("the name " + hope + " is cool");
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
} //taken from the portation class
System.out.println(points);
//damn.post();
//damn.justPoints();
}
}
portation: not in use
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
the code that doesn't work
MaintTest:
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
damn.post();
damn.justPoints();
}
}
portation:
public class portation {
public void justPoints() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
int points = 0; //setup the points variable
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println(points);
}
public void post() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
System.out.println("the name " + hope + " is cool"); //printed what the user typed
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
}
}
}
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
when I use the way that doesn't work this is what runs:
What your name my guy? chris
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.post(portation.java:21)
at MainTest.main(MainTest.java:9)
What would be the answer I'm looking for? I would like to know, why am I getting this error and what do I need to do to fix it?
The problem comes from the fact that System.in is a specific InputStream - it is static and only created once. In your case, you read from it once and immediately close it (when you close the Scanner). When you try to read from a closed stream, it will throw an exception, NoSuchElementException in this case. When working with files it usually isn't a problem because you could always create a new InputStream.
What you need to do here is to make sure you will close the InputStream only when you're done with reading everything. You could make the Scanner variable static, create a new method for closing it and call it only when you're done with reading.
So I've been given the method below and I'm not allowed to change it. What I need is it to create a couple of objects with the variables below but keeps coming up with an error that says "The constructor menu(int, String, String) is undefined." Am I doing something wrong?
import java.util.Scanner;
import java.util.*;
public class menu {
private static void addNewStudent()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the correct details below");
System.out.println("ID: ");
int userId = scanner.nextInt();
System.out.println("First name: ");
String userFirst = scanner.next();
System.out.println("Last name: ");
String userLast = scanner.next();
System.out.println("English assignment 1 mark: ");
int english1 = scanner.nextInt();
System.out.println("English assignment 2 mark: ");
int english2 = scanner.nextInt();
System.out.println("English assignment 3 mark: ");
int english3 = scanner.nextInt();
System.out.println("Math assignment 1 mark: ");
int math1 = scanner.nextInt();
System.out.println("Math assignment 2 mark: ");
int math2 = scanner.nextInt();;
System.out.println("Math assignment 3 mark: ");
int math3 = scanner.nextInt();
menu userStudentObj = new menu(userId, userFirst, userLast);
menu userEnglishObj = new menu(english1, english2, english3);
menu userMathObj = new menu(math1, math2, math3);
// Asks the user for the student information (ID, First, Last, Assignments)
// Then creates the appropriate objects and adds the students to the student list
I would expect to have created 3 new object that contain the user input variables within the objects if that makes sense.
The main problem is that you didn't specify any non default constructor, to create objects so compiler have no ideas what do you want to create if object is not specified for that. But there is another problem. Your object is designed in not the best way. So if you want to handle it correctly you could change your class design so you handle it in right way.
For example you could make it a bit different, like in this example (it's not perfect, it still can be more separate and better designed):
class User {
int userId;
String userFirstName;
String userSecondName;
private ArrayList<Integer> mathSums = new ArrayList<>();
private ArrayList<Integer> englishSums = new ArrayList<>();
User(int userId, String userFirstName, String userSecondName) {
this.userId = userId;
this.userFirstName = userFirstName;
this.userSecondName = userSecondName;
}
public void addMathSums(int mathSums) {
this.mathSums.add(mathSums);
}
public void addEnglishSums(int englishSums) {
this.englishSums.add(englishSums);
}
}
So by the help of this class you could change the way, how you define and set the values for your object and it would look like that:
1) You define constructor with arguments so you're able to use it for object creation:
User user = new User(userId, userFirst, userLast);
2) Then you can add sums into ArrayLists that are member variables (fields) in User class:
user.addMathSums(math1);
user.addMathSums(math2);
user.addMathSums(math3);
user.addEnglishSums(english1);
user.addEnglishSums(english2);
user.addEnglishSums(english3);
It could be performed in different ways using arrays, lists or other data structure, but you really need to pay attention for your class design. More time you spend on designing object less modifications you will need later.
3) You probably want to interact with this object so you need to get a reference for it somehow. You could change the method signature so you will "return" created object after you finish your input. So you need to make some changes:
On the method change the signature return type to User:
private static User addNewStudent() { ... }
Then add return for that and return created user:
private static User addNewStudent() {
/* code */
User user = new User(userId, userFirst, userLast);
/* add sums */
return user;
}
4) Use this method in your main():
public static void main(String[] args) {
User createdUser = User.addNewStudent();
}
This question already has answers here:
Is it possible in Java to access private fields via reflection [duplicate]
(3 answers)
Closed 7 years ago.
My template opens with a menu of options and the user inputs something between 1-3 to select one of the three options.
When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input a String teamMemberFirstName and a char firstInitialLastName. Then it will write the input to a private arraylist located in another class TeamMember.
Once they have input the info in option 1 and 2, they can choose option 3. It allows you to print the list of inputted names based on which team number you put them on.
I am not sure how, in option 3, to call the private arraylist from the TeamMember class teamList. Any guidance on how to proceed with this step? My code is below.
Main class:
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
System.out.println("Success!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
if (input.equals("3")){
for (int a = 0; a < numberList.size(); a++) {
Team addTeam = numberList.get(a);
//Not sure what to put where there are ????'s - I tried a few ideas and stuff I found online, but nothing worked
//I assume I call the method/class here????
System.out.println("Team: " + addTeam.findTeam() + " Members: " +
"I will put the member called from the arraylist here????");
}
}
}while (stayInLoop == true;)
}}
TeamMember class:
public class TeamMember {
private final String teamMemberFirstName;
private final char firstInitialLastName;
private ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
}
You cannot directly access private fields from other classes. Either move your list to the Team class or create a getter to retrieve the list.
In a public class, you can return a private object in a public method. This seems like the easiest way in this project. Add a new method to your TeamMember class, and have it return teamList:
//inside your TeamMember class, anywhere after you assign the private variable
public static ArrayList show(){
//the static keyword, in short, will make the method callable without a class instance.
return teamList;
}
Since the TeamMember method show() is now static, you should be able to simply call TeamMember.show() and get the ArrayList.
Important note: In order for this to work, you must make the private arraylist static too. A static object cannot call a non-static object.
This will turn it into private static ArrayList<TeamMember> teamList = new ArrayList<>();
In the Main class, like I said above, simply call TeamMember.show(). You do not need to create an instance.
If you change your teamList to public instead of private your Main class will be able to access the variable. When you make something private in Java you're basically making that instance variable accessible only through the class that it's instantiated in. If you want the variable to be visible to other classes for reference you should make it public
Since the assignment calls for it, you're going to need to define a getter and setter for your 'teamList' variable.
public void setArray(ArrayList newTeamList){
teamList = newTeamList;
}
public ArrayList getArray(){
return teamList;
}
This'll allow you to access the private variable through the methods
What I have below is producing the desired results by print some employee details along with weekly / monthly wages as appropriate.
However I understand that I should not be inputting data in the constructor as I've done.
I need to prompt for a hours worked value only for "PartTimeEmployees", just not the way I've done it.
I've tested with For-Each loops, Enhanced For loops and using the instanceOf operator.
If I could get some guidance/hints or examples of how to accomplish what is currently being done in the constructor, but in the TestEmployee class instead that would be great.
Mostly I'm not sure how to even describe what I'm trying to achieve. This hinders Googling somewhat. (Help with a better title would also be great)
Thanks in advance.
public class TestEmployee
{
public static void main(String[] args)
{
int size;
Employee[] employees = new Employee[4];
employees[0] = new FullTimeEmployee("Jane", 26000);
employees[1] = new PartTimeEmployee("Jack");
employees[2] = new FullTimeEmployee("Lucy", 52000);
employees[3] = new PartTimeEmployee("Lenny");
for(int i = 0; i < employees.length; i++)
{
employees[i].print();
}
}
}
Class: PartTimeEmployee - Constructor:
public PartTimeEmployee(String thisName)
{
super(thisName);
System.out.println("Please enter the number of hours worked by " + thisName + ": ");
numHours = keyboard.nextInt();
setHours(numHours);
}
If I get your question, below might fit with your need -
First of all create generic Employee class -
class Employee {
private String name;
private int workingHours;
private final boolean IS_PART_TIME_EMP;
public Employee(String name, int workingHours) {
this.name = name;
this.workingHours = workingHours;
this.IS_PART_TIME_EMP = false;
}
public Employee(String name) {
this.name = name;
this.IS_PART_TIME_EMP = true;
}
public String getName() {
return name;
}
public int getWorkingHours() {
return workingHours;
}
public void setWorkingHours(int workingHours) {
this.workingHours = workingHours;
}
public boolean isPartTimeEmployee() {
return IS_PART_TIME_EMP;
}
}
Now you can use it as per your requirement.
Employee[] employees = new Employee[4];
employees[0] = new Employee("Jane", 26000);
employees[1] = new Employee("Jack");
employees[2] = new Employee("Lucy", 52000);
employees[3] = new Employee("Lenny");
Scanner sc = new Scanner(System.in);
for (Employee employee : employees) {
if(employee.isPartTimeEmployee()) {
System.out.println("Please enter working hours by " + employee.getName() + ": ");
int numHours = sc.nextInt();
employee.setWorkingHours(numHours);
}
}
Constructor is not meant for user input.Its main intention is to initialize object of that class.
Instead of doing that in constructor,you can try something like this
employees[1] = new PartTimeEmployee("Jack");
System.out.println("Please enter the number of hours worked by " + employees[1].getName()+ ": ");
numHours = keyboard.nextInt();
employees[1].setHours(numHours);
You most likely will have some logical main loop in your program, like
while(!quit) {
// 1. ask if you want to add part time or full time employee
// 2. ask proper questions
// 3. call correct constructor
}
Writing such small pseudo code algorithm should be self explanatory and get you going.
Step one: presentation of options available for user and reading user input.
Step two: performing actions depending on user input from step 1
Step three: final call to proper constructor depending on results from steps 1 and 2
If I understood your question correctly (which I'm really not sure of) you want to prompt for the employee data in the main method.
In that case I'd use a loop and query the following things:
name of the employee
does the employee work full time? (y/n)
if yes: what is the wage? (assume hours = whatever a full time employee works a day)
if no: how many hours? (and probably the hourly wage as well)
Then use that information to construct an Employee object (I don't see any need for the subclasses here).
I am a few weeks into my java class and one of my homework assignment I can't seem to figure out. Here is the assignment
"Display a menu of three kinds of cookie. Prompt the user for what kind of cookie they want using the GetGoodInt(public static int GetGoodInt(int tLow, int tHigh) if the input is too high say to high, if its too low, say to low, if not a int display error) jar.
Create a cookie, give it to the Oven to cook it, then give it to a Person to eat it.
!text bolded like This and then followed by declarations is a class that is both required and unchangeable!
Cookie
boolean mCooked
String mFlavor
Cookie( String tFlavor ) // This is a constructor. Note that when you have this, it won’t let you use the lazy default constructor.
String toString() // This lets you output a cookie to the console. Never call it manually.
Oven
void Cook( Cookie tCookie ) // Just sets mCooked to true
Person
void EatCookie( Cookie tCookie ) // If it is cooked, output the type and how good it is. If it isn’t, print one sentence about the symptoms of salmonella.
Sample Output:
What type of cookie would you like?
1) Chocolate chip
2) Peanut butter
3) Oatmeal raisin
4
Not a choice.
r
Not a number
3
That was a great Oatmeal raisin cookie."
This is what I have coded so far but I am having trouble with what i assume isconstructor, so far everything I have tried gives me a Run time error.
Here is all my code
package mainpackage;
public class Cookie
{
public Boolean mCooked;
public String mFlavor;
public Cookie(String tFlavor)
{
tFlavor=mFlavor.toString();
}
public String toString()
{
int i = Week9Jar.Input.GetGoodInt(1, 3);
String tFlavor= Integer.toString(i);
if(tFlavor=="1")
mFlavor="Chocolate Chip";
else if(tFlavor=="2")
mFlavor="Peanut Butter";
else if(tFlavor=="3")
mFlavor="Oatmeal Raisin";
return mFlavor;
}
}
package mainpackage;
public class Oven
{
void Cook(Cookie tCookie)
{
tCookie.mCooked=true;
}
}
package mainpackage;
public class main {
public static void main(String[] args) {
// Week 9 Homework part I
Cookie tCookie=null;
Oven tOven= new Oven();
Person tPerson = new Person();
System.out.println("What type of Cookie would you like?");
System.out.println("1) Chocolate Chip");
System.out.println("2) Peanut Butter");
System.out.println("3) Oatmeal Raisin");
//get Type from user
tCookie=new Cookie(Week9Jar.Input.GetGoodInt(1, 3));
tOven.Cook(tCookie);
tPerson.EatCookie(tCookie);
}
}
Your constructor for Cookie is wrong: you take in tFlavor as an argument and assign a value to it, and after execution of the constructor, that value is lost. What you probably want is:
public Cookie(String tFlavor) {
mFlavor = tFlavor;
}
You don't need to call toString on String objects: they're already strings!
Also, it's not good practice to access data members of a class from another class, even if it's from the same package:
public void Cook(Cookie cookie) {
cookie.setCooked(true);
}
And add a setCooked method inside your class Cookie:
public void setCooked(boolean b) {
mCooked = b;
}