I've been trying to wreck my brain around this for days.
I need to make a method that is going to ask for the user input via the keybaord.
I've written it as
private static String getFromUser(String question){
String s = " ";
System.out.print(question);
while(in.hasNext()){
s = in.next();
//return s;
}
return s;
}
or
private static String getFromUser(String question){
String s;
System.out.print(question);
s = in.nextLine();
return s;
}
HOWEVER
When I "uncomment" a skeleton code:
public static void create() {
in = new Scanner(System.in);
String name = "";
String address = "";
//ask the user for the name and address of the company receiving the invoice
//String name = getFromUser("name of company to invoice"); // ******TASK ONE******
//String address = getAddress(); // ******TASK TWO******
It keeps stating : "variable name is already defined in method create()". BUT I'm not allowed to change the codes that has already been written. HENCE, I'm only allowed to remove the "//" comment lines.
Do I just return a string or would I require to use method overloading ( I don't fully understand method overloading, tbh).
Please Advice or give tips. Thank you very much.
You have defined the variable two times in the same method scope, what you need to do is to remove the second declaration of the variables like :
String name = "";
String address = "";
// here don't declare the variable again, just use it like
name = getFromUser("name of company to invoice");
address = getAddress();
If you're already declaring the variable here:
String name = getFromUser("name of company to invoice");
Then you don't need to also declare it here:
String name = "";
Just remove the shorter one.
You can declare it on one line and then use it later:
String name = "";
name = getFromUser("name of company to invoice");
or do both on one line (which you already do):
String name = getFromUser("name of company to invoice");
But you can't declare the same variable twice in the same scope.
The other two answers are correct in that you cannot define a variable twice within the scope of a single method. Are you permitted comment out lines? eg. you could comment out the initial definition like so.
//String name = "";
String address = "";
//ask the user for the name and address of the company receiving the invoice
String name = getFromUser("name of company to invoice");
//String address = getAddress();
and then do the same for address once you are ready to use task two.
If this is not permitted then you will have to approach your instructor (assuming this is for a class) and indicate it is not possible.
Id rather use the Scanner class instead. Makes it look cleaner:
private static String getAnswerFromUser(String question){
Scanner input = new Scanner(System.in);
System.out.println("Question: " + question);
System.out.print("Answer: ");
String answer = input.next();
return answer;
}
Related
I have two classes, treatments and booking, Ive applied aggregation to them. In the main driver class the user has to be able to add new treatments so that information will all be saved into an array list. I get an error when i try to get it to insert the user input into the array. I would appreciate it if someone told me what I was doing wrong.
Treatments class
public class treatment {
String treatment_type;
String treatment_procedure;
// aggregated
booking booking;
treatment( String treatment_type, String treatment_procedure, booking bookings ){
this.treatment_type = treatment_type;
this.treatment_procedure = treatment_procedure;
this.booking = bookings;
}
}
Bookings class
public class booking {
String patientname;
String doctorname;
String date;
String time;
public booking (String p, String d, String da, String t) {
this.patientname = p;
this.doctorname = d;
this.date = da;
this.time = t;
}
}
Driver class
public static void treatments(){
Scanner sc = new Scanner(System.in);
System.out.println("Please provide treatment information");
System.out.println("Enter the Patient's name :");
String pname = sc.next();
System.out.println("Enter the doctors name :");
String dname = sc.next();
System.out.println("Enter the date of the appointment :");
String date = sc.next();
System.out.println("Enter your time of appointment :");
String time = sc.next();
System.out.println("Enter the type of treatment :");
String treattype = sc.next();
System.out.println("Enter the specifics of the procedure :");
String specifics = sc.next();
treatment newtreatment = new treatment(pname,dname,date, time, treattype, specifics);
treatmentlist.add(newtreatment);
System.out.println("The dentist has been registered Successfully");
}
The line that is underlines in red is
treatment newtreatment = new treatment(pname,dname,date, time, treattype, specifics);
The error message says the following
required: String,String,booking
found: String,String,String,String,String,String
reason: actual and formal argument lists differ in length
I know the length isnt right so to test it I minimized it to just 3 values to see if the error would go off but one was still underlined saying the following
incompatible types: String cannot be converted to booking
Anybody got any ideas? Thank you
The constructor for the treatment class takes two String arguments and a booking argument.
treatment( String treatment_type, String treatment_procedure, booking bookings ){
When you use it, you call it with six String arguments.
new treatment(pname,dname,date, time, treattype, specifics);
Now, your booking class' constructor takes four String arguments, so I suspect you meant to use four of the String arguments to construct a booking object that you'd pass as an argument to the treatment constructor.
Something like:
new treatment(treattype, specifics, new booking(pname, dname, date, time));
I have an array of objects, and i'm looking to check if a variable in the object has a particular name. Eventually id like to do it for every object in the array, but i only was testing it on the first index. Im not sure if an arraylist would be better for this. (I have separate faculty/classroom/course/textbook/name classes)
public static void startCourse(){
Course[] course = new Course[4];
Scanner input = new Scanner(System.in);
for(int i = 0;i < course.length;i++){
System.out.println("Enter Course Number and course title: ");
String courseNumber = input.nextLine();
String courseTitle = input.nextLine();
course[i] = new Course(courseNumber,courseTitle);
//FACULTY
System.out.println("Faculty: /nEnter First Name: ");
String facultyfName = input.nextLine();
System.out.println("Enter Last Name: ");
String facultylName = input.nextLine();
course[i].setFaculty(new Faculty(facultyfName,facultylName));//doesnt set name in constructor???
course[i].getFaculty().getName().setfName(facultyfName);
course[i].getFaculty().getName().setlName(facultylName);
course[i].setTextbook(new Textbook("Intro to java","123456",59.99));
course[i].setClassroom(new Classroom("R540",26,true));
Student student1 = new Student("Yulissa","Lucero");
Student student2 = new Student("Aaron","Folborg");
Student[] students = {student1,student2};
//input.close();
System.out.println(course[i]);
//System.out.println(students);
}
System.out.println(course[0].getFaculty().getName().equals("Ben"));
}
There is confusion seeing your code, when you are setting Faculty name you are using below statements :
course[i].getFaculty().getName().setfName(facultyfName);
course[i].getFaculty().getName().setlName(facultylName);
Which made be believe that getName() would be returning some kind of object having two properties fname and lname
But when you are comparing the faculty name, you are using below statement :
course[0].getFaculty().getName().equals("Ben")
How can you compare Object with String, you should either use something like getfName() or getlName().
In context of code :
course[i].setFaculty(new Faculty(facultyfName,facultylName));//doesnt set name in constructor???
should be valid when Course class has a setter for Faculty faculty attribute and Faculty class has a constructor for attributes of Name name field within it as:
Faculty(String fname, String lname) {
this.name.setfName(fname);
this.name.setLname(lname);
}
The comparison should hold true when the first input provided to
facultyfName = input.nextLine();
is "Ben" and then comparing the first name of the faculty using :
System.out.println(course[0].getFaculty().getName().getfName().equals("Ben"));
I am attempting to create a list of bank records. Each record consists of a first name, last name, phone number, and balance. In the first class I ask the user for this information, then create a new instance of the records class to add to the list. However, as I add more records it replaces all records with the most recent one, which you can see with my showAllRecords() method. How do I fix this?
The add and showAllRecords method in the main class. These methods are called from a switch statement in the main method:
private static void showAllRecords()
{
if(records.bankRecords.size() == 0)
System.out.println("There are no records.");
else
for (int i = 0; i < records.bankRecords.size(); i++)
{
System.out.println(records.bankRecords.get(i));
}
}
private static void add()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the first name: ");
String firstName = scan.next();
System.out.print("Please enter the last name: ");
String lastName = scan.next();
System.out.print("Please enter the phone number: ");
String phoneNumber = scan.next();
System.out.print("Please enter the balance: ");
int balance = scan.nextInt();
bankRecords.add(new records(firstName, lastName, phoneNumber, balance));
}
The records class
public class records
{
public static String firstName;
public static String lastName;
public static String phoneNumber;
public static int balance;
LinkedList<records> bankRecords = new LinkedList<records>();
public records(String tFirstName, String tLastName, String tPhoneNumber, int tBalance)
{
firstName = tFirstName;
lastName = tLastName;
phoneNumber = tPhoneNumber;
balance = tBalance;
}
}
The problem occurs because all the fields in records class are static. Remove the static keyword from the declarations of fields. As they are static whenever you create a new object of records class you overwrite those static fields.
Static fields belong to the class not to the object.
Remove the LinkedList instance that you have declared in records class. Why are u doing that. Declare it in your main class and try to use ArrayList which I think is better in your case. The reason is that records has static fields
Why your class name starts with small letter. Its a very very bad practice.
You have an inherent planning problem.
There is a difference between the entity "Bank Record", which includes, as you said, a name, balance etc., and the entity "List of Bank Records", which includes, well, a variable number of bank records.
Your "records" class (please use a capital letter in the beginning of a class name) tries to mix both. So you have both a record and a list inside it. You should separate the two entities. You then create a new "Record", and add it to the "ListOfBankRecords" objects.
Also, it seems that you have both a variable and a variable called "records". This is also why a capital letter would have been good. You shouldn't have a variable that has the same name as a class.
When creating e.g an address book I also want a method for searching it.
Imagine I go for an object like this:
public class someone {
private static someone [] addressBook = new someone[150];
private String firstName;
private String lastName;
private String address;
//...
public someone(String firstName, String lastNameame, String adress/*,...*/){
this.firstName=firstName;
//...
}
Now I'm planning on searching for someone using user input and Scanner. First, the user should declare for what (s)he is searching in gerneral:
public static void searchSomeone(){
System.out.println("What do you want to search for?: ");
Scanner sc1 = new Scanner(System.in);
String userInput1 = sc1.next(); // e.g. userInput1="firstName"
Second, the user is asked for the exact value (s)he is searching for:
System.out.println("Enter a " + userInput1 + ": ");
Scanner sc2 = new Scanner(System.in);
String userInput2 = sc2.next(); // e.g. userInput2="Peter"
for (int i=1;i<150;++i){
if(getAddressBook[i].**"Value of userInput1"**.contains(userInput2)){ // here is my problem!*
System.out.println("Congrats, we've found someone! ");
}
}
}
Is there a way to use the value of the input as a call for the member variable?
In this case the argument should 'become'
if(getAddressBook[i].firstName.contains(userInput2)){}
I tried to implement another method like getInputValue that simply returns the String but it didn't work here.
If there is no such solution I will have to include code for every member variable separately which I really dont want to!
Hope you get my idea! And please be kind I'm quite new to forums. :P
FYI
What I was trying to do here is not possible within Java I guess. However Visual Basic provides a "var" keyword and also something called "generics". For everyone who has the same problem may find a solution there.
I am having a small problem I am trying to print the contents of a couple of variables which are located in a a private method. but I simply keep getting 'Can Not Find Symbol'
Below is the code that I am trying to read the data from (including the println) also I am very new to java.
private void createBooking()
{
String title;
String firstName;
String lastName;
String bookingNo;
String roomType;
System.out.print("Enter title: ");
title = keyboard.next();
System.out.print("Enter first name: ");
firstName = keyboard.next();
System.out.print("Enter last name: ");
lastName = keyboard.next();
System.out.print("Enter booking number: ");
bookingNo = keyboard.next();
System.out.print("Enter room type: ");
roomType = keyboard.next();
aBooking = new Booking (title, firstName, lastName, bookingNo, roomType);
}
public void printCustomerName()
{
System.out.println (createBooking.title);
}
You probably want to put these variables as member variables, and then simply access it without using the .-operator.
class BookingClass {
// You also seem to need the following:
Booking aBooking;
String title;
String firstName;
String lastName;
String bookingNo;
String roomType;
private void createBooking() {
System.out.print("Enter title: ");
title = keyboard.next();
System.out.print("Enter first name: ");
firstName = keyboard.next();
System.out.print("Enter last name: ");
lastName = keyboard.next();
System.out.print("Enter booking number: ");
bookingNo = keyboard.next();
System.out.print("Enter room type: ");
roomType = keyboard.next();
aBooking = new Booking(title, firstName, lastName, bookingNo, roomType);
}
public void printCustomerName() {
System.out.println(title);
// ...should perhaps be
// System.out.println(firstName + " " + lastName);
}
}
Since you do create a Booking instance however, you may want to get rid of title, firstName, lastName, bookingNo and roomType and put them in the Booking class instead. And then access them through aBooking.getTitle() and so on...
When you do aBooking = new Booking(...) you're creating a new Booking object with all those attributes and storing it in the aBooking field (I'm guessing it's a field since it's not declared anywhere). This means you have a aBooking field that holds all those attributes (assuming the Booking constructor saves the parameters). So, to access those fields you go through the aBooking field. Probably something like this:
System.out.println(aBooking.getTitle());
or, if you're not using getters (you should!):
System.out.println(aBooking.title);
The variables you declare inside the createBooking method stop "existing" once you leave the method. They're not accessible in any way (well, almost).
You cannot access to variable of a method and cannot use a method as a class instance using a dot operator.
createBooking.something is illegal , you can use that method: createBooking()
You may want to consider changing the return type of the createBooking() method from 'void' to 'Booking', and then the last line would become:
private Booking createBooking()
{
...
...
return new Booking(title, firstName, lastName, bookingNo, roomType)``
}
After that, your printCustomerName() might look like something like:
public void printCustomerName()
{
Booking booking = createBooking();
System.out.println (booking.title); // if title is visible, which it probably shouldn't be
//or
System.out.println (booking.getTitle()); // if such a method exists...
}
I don't understand totally what you wanna do. But i think you want something like this:
public String printCustomerName() {
// This creates the booking object (aBooking)
createBooking();
// You can access the firstname lastname like that (I assume that you have a getter method implemented..)
return aBooking.getFirstName() + " " + aBooking.getLastName();
}
But the createBooking() you should move to another place. Maybe into the Constructor and call it there..