simply i have this file reading it and storing it into array and then want to call the values back later to print them
my text file
`101
12-7-2017
14-7-2017
some name
00000.. phone number
520
29-8-2017
1-9-2017
some name
00000.. phone number
1020
30-12-2017
1-1-2018
some name
00000.. phone number`
this the main test code
public class test {
public static void main(String[] args) throws ParseException, FileNotFoundException{
Scanner res = new Scanner (new File("reservations.txt"));
int z=0;
do{
int room_numb = res.nextInt();
String cInr=res.next();
String cOutr=res.next();
String Fname=res.next();
String Lname=res.next();
String phone_numb=res.next();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date cIn = df.parse(cInr);
Date cOut = df.parse(cOutr);
Reservation.reserv[z]=new Reservation (room_numb, cIn, cOut, new Guest(Fname, Lname, phone_numb));
z=z+1;
}while(res.hasNext()==true);
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
}
my classes are these 3
reservation
public class Reservation {
static Reservation[] reserv= new Reservation[200];
Guest guest;
int room_numb;
Date in, out;
public Reservation(int room_numb, Date in, Date out, Guest g) {
this.room_numb = room_numb;
this.in = in;
this.out = out;
g= guest;
}
public int getroom_numb(){
return room_numb;
}
public Date getin(){
return in;
}public Date getout(){
return out;
}public Guest getguest(){
return guest;
}
Room
public class Room {
int room_numb;
String indate;
public void setRoom(int i) {
room_numb =i;
}
public int getRoom(){
return room_numb;
}
and guest
public class Guest {
String Fname;
String Lname;
String phone_number;
public Guest(String fname, String lname, String phone_numb ){
Fname=fname;
Lname=lname;
this.phone_number=phone_numb;
return;
}
public String getFname(){
return Fname;
}
public String getLname(){
return Lname;
}
public String getphone_number(){
return phone_number;
}
}
i have been able to get all variables such as room numb/checkin date and checkout date/ but when ever i ask for guest through
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
it gives me null which mean it doesn't reference to anything
so i am not able to use String Fname=Reservation.reserv[0].getguest().getFname();
so how to get the data from guest in reservation array?
Note: i am new to java so be gentle with ma please :) also the sysout is just for testing in the main method
Thanks :).
I'm not going to fix your code for you. Doing that is part of your homework. However, here are a couple of hints to start you in the right direction.
Hint: Look carefully at how your Reservation constructor (tries to) initialize the object's fields. See the problem?
Hint 2: The problem that tripped you up is that getguest() is returning null .......
While I have your attention, there are numerous style errors in your code, but the worst is your complete disregard of the Java converions for identifier names:
A class name must start with a capital letter and be in camel-case: Test not test.
A method or variable name must start with a lower case and be in camel-case; e.g. getGuest not getguest.
We don't need or use "hungarian" notation in Java. The type of a variable is expressed in the type declaration.
Your choice of variable names is inconsistent and "uninspired".
And "numb" is what happens when your fingers get cold.
Related
I want to create the below class
associatename:String
workstatus:String
associate() :constructor
getassociatename():String
setassociatename(String):void
getworkstatus()String
tracksassociatestatus():int
setworkstatus(String):void
The trackAssociateStatus method takes the number of days as argument and sets the work status of the associate based on the number of days. The first 20 days they learn “C”, the next 20 days they learn “Java” In the Main class invoke the trackAssociateStatus method and find the work status and display the output.
output:The associate abc work status:Project phase
I tried this....But i got error
//associate class
public class associate{
private int associatename;
private String workstatus;
private int days;
void associate()
{
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus();
setworkstatus();
}
public int getassociatename()
{
return associatename;
}
public void setassociatename(int associatename)
{
this.associatename=associatename;
}
public String getworkstatus()
{
return workstatus;
}
public void tracksassociatestatus(int days)
{
if(days<20)
setworkstatus("C");
else
setworkstatus("Java");
}
public void setworkstatus(String workstatus)
{
this.workstatus=workstatus;
}
}
//main class
associate a =new associate();
Scanner in=new Scanner(System.in);
int associateid=0;
String workstatus=null;
int days=0;
System.out.println("Enter the associateid:");
associateid=in.nextInt();
a.associateid=(associateid);
System.out.println("Enter the no of days:");
days=in.nextInt();
a.trackassociatestatus();
System.out.println("The id is "+a.getassocaiteid()+" work status "+a.getworkstatus());
Based on your (seemingly) UML spec, your class would look like the following:
public class Associate {
private String associateName;
private String workStatus;
public Associate() {
// This constructor is optional, a no-args constructor is added by the compiler to any class not explicitly naming a constructor.
}
public String getAssociateName() {
return associateName;
}
public void setAssociateName(String associateName) {
this.associateName = associateName;
}
public String getWorkStatus() {
return workStatus;
}
public void setWorkStatus(String workStatus) {
this.workStatus = workStatus;
}
public int tracksAssociateStatus() {
// TODO write logic here
return 1; // TODO change to whatever you need to return
}
}
You were specifying int for getAssociateName, when associateName is a String. This won't work; you need your getter return type to be the same as your field data type, or you need to convert the data to the method's return type. (The former is best practice).
Constructors don't specify a type, the class name is used and the compiler will understand what you want to do (which is return a new instance of the class). Therefore, your void associate() will tell the compiler "create a method called associate that doesn't return anything".
Well, would be nice if you provide the error itself for us.
But meanwhile, have you notice that your tracksassociatestatus method recieves an integer parameter days, and your constructor passes nothing to it?
So try changing your constructor to be something like:
Public associate() {
getassociatename();
setassociatename();
getworkstatus();
tracksassociatestatus(10);
setworkstatus();
}
For a cleaner code, check the other answer.
If you still have errors, please share them.
import java.util.*;
public class Associate
{
private String associateName;
private int workStatus;
private int days;
Scanner sc = new Scanner(System.in);
public String getAssociateName()
{
System.out.println("Enter the Associate id:");
associateName = sc.nextLine();
return associateName;
}
public void setassociatename(int associatename)
{
this.associateName=associateName;
}
public String tracksAssociatename()
{
return associateName;
}
public int getWorkStatus()
{
System.out.println("Enter the number of days");
days = sc.nextInt();
return days;
}
public void setWorkStatus(String workStatus)
{
this.workStatus=workStatus;
}
enter code here
public `enter code here`int tracksAssociateStatus()
{
return days;
}
public static void main(String args[])
{
Associate obj = new Associate();
obj.getAssociateName();
obj.getworkstatus();
System.out.println("The Associate name "+obj.tracksAssociatename()+" work Status "+obj.tracksAssociateStatus());
}
}
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
I've created a simplified version of my current assignment for my programming course.
I've created a test program that asks the user for an input, studentName, studentName is then validated through another class. My end goal is to print out a method called toString() that holds the value the user has entered for the studentName. Right now my program returns null, not the value of studentName. The problem is I'm not sure how to properly set the values with a constructor.
If you could set up a proper constructor and a way to properly print the value the user has entered through the command prompt, I would appreciate it!
Here is the class that contains the main method. Note: I may have declared too many class objects because I was in a hurry.
import java.util.Scanner;
public class TestMcTest
{
TestMcTest2 test3 = new TestMcTest2();
public static void main(String[] args)
{
TestMcTest test2 = new TestMcTest();
TestMcTest2 test = new TestMcTest2();
test2.getStudentInfo();
System.out.println(test.toString());
}
public void getStudentInfo()
{
int valid = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter a name for a student");
valid = test3.getStudentName(input.nextLine());
}while(valid == 0);
}
}
Here is the class that holds the validation and the toString() method that I want to call into the main method of the class with the main method.
public class TestMcTest2
{
private String studentName;
public String setStudentName()
{
return studentName;
}
public int getStudentName(String studentName)
{
int valid = 0;
if (studentName.length() != 0)
{
valid = 1;
this.studentName = studentName;
}
return valid;
}
public String toString()
{
return this.studentName;
}
}
You dint set the value of variable studentName so the default value of string is printed i.e. null
In TestMcTest you have do
TestMcTest2 test = new TestMcTest2();
test.setStudentName("singhakash");
System.out.println(test.toString());
and in TestMcTest2 change
public void setStudentName(String studentName){
this.studentName = studentName;
}
this will give the expected output.
Btw your method name says opposite of its functionality.
If you could set up a proper constructor and a way to properly print
the value the user has entered through the command prompt, I would
appreciate it!
public class TestMcTest2{
....
public TestMcTest2(String s){
this.studentName = s;
}
}
You have to use the newly constructor now like this:
TestMcTest2 test3 = new TestMcTest2("hot name");
And you can print it out like this after your do-while
System.out.println(test3.toString());
And I'm pretty sure you need the #Override annotation at the toString() method.
EDIT:
#Override <- add this
public String toString()
{
return this.studentName);
}
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) {
I am trying to make a class and a separate printer class for post cards. The idea is to make a postcard that can take user inputs for sender, recipient, and occasion. Then add in something that allows us to send the same postcard to another friend. This is my post card class
public class Postcard
{
private String message;
//define other variables that you need in this class
private String sender;
private String recipiant;
private String occasion;
private String print;
// Methods go here
public Postcard()
{
String message = "Happy holidays too ";
String sender = "Michael";
String recipiant = "";
String occasion = "";
}
public void setmessage(String m)
{
this.message = m;
}
public void setSender(String s)
{
this.sender = s;
}
public void setRecipiant(String r)
{
this.recipiant = r;
}
public void setOccasion(String o)
{
this.occasion = o;
}
public String print()
{
print = message + sender + recipiant + occasion;
return print;
}
}
and this is the post card print class
import java.util.Scanner;
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "Happy Holiday to ";//write your msg here
Postcard myPostcard = new Postcard(); // use the constructor method
//use the mutator method to set the name of the recipient
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
myPostcard.print();
//write the code to send the same msg to another friend
System.out.println("Do you want to send another? Type 'yes' or 'no' ");
String choice = op.nextLine();
while (choice != no)
{
String text = "Happy Holiday to ";
Postcard myPostcard = new Postcard();
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
}
}
}
Error's appear in the while loop saying that varriable no doesn't exist and when commented out, nothing happens. Virtual machine is running, but nothing happens. Any help would be greatly appreciated
The line:
while (choice != no)
Is looking for a variable called no, not a string constant. You want:
while (!choice.equals("no"))
Or, the case-insenstive method:
while (!choice.equalsIgnoreCase("no"))
One thing to point out - since the value of choice never changes once inside the loop, you'll basically be looping forever. You'll probably want to ask again after each iteration of the loop. You can probably just set the initial value of choice to an empty string, then immediately start the loop when the program begins. This would allow you to remove the redundant code above the loop.