Java Constructor Syntax Issue - java

I need a little help understanding constructors. It isnt full code I just need help understanding one part. My code is as follows:
School.java
public class School {
private String name;
private int busNumber;
enter code here
public School (String name) {
this.name = name;
}
public String getSchoolName() {
return name;
}
public int getBusNumber() {
return bus Number;
}
Main.Java
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
School s1 = new School(school1);
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
School s2 = new School(school2);
System.out.println("School 1 is " + s1.getName());
System.out.println("School 2 is " + s2.getName());
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
//Now what I want to do is send the bus numbers to getBusNumber.
//How do I send bus1 so I can use s1.getBusNumber(); to call the number later! I feel like this should be so easy but I can't grasp it or find how to do it anywhere. I also do not want to use a set function. Any syntax help would be awesome!!
Thanks!

So if you need to not use a setter, you probably need to put it in the constructor.
So your constructor would be
public School (String name, int busNumber) {
this.name = name;
this.busNumber = busNumber
}
and your code would look like this
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
System.out.println("School 1 is " + school1);
System.out.println("School 2 is " + school2);
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
int intBus1 = Integer.parseInt(bus1)
School s1 = new School(school1, intBus1);
Then later in your code you can call get s1.getBusNumber() if needed

With the code you posted here is not possible since the busNumber is declared private...
You need (is a good practice) to define a setter for the member bus in the class School, you can to use public members but is not a good oop design since you need to change the access of the busNumber to public...
public void setBusNumber(int number) {
this.busNumber = number;
}
and call it from the main java
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
s1.setBusNumber(bus1);
Be aware you need to validate that what you read is a number because next line is returning strings...

Related

How to pass a string array or integer value from a class to another using java?

I created a simple console based student system where basically the program will ask if you want to input name of students or view the list of names you inputted. The flow of the output is as shown below:
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 1
Enter number of students to input: 3
****************************************
Student No. 1
Enter full name: Alpha Jones
****************************************
Student No. 2
Enter full name: Beta Jones
****************************************
Student No. 3
Enter full name: Gamma Jones
Do you wish to proceed back to menu?(y/n): y
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 2
******LIST OF STUDENTS******
NULL
NULL
NULL
Firstly, I input three new students names Alpha Jones, Beta Jones and Gamma Jones but when I chose to view all names, everything is null. The three names should appear.
Here is the code for Student Class:
public class Student {
private String[] names;
private int numInput;
public Student(){
}
public Student(String[] fullName, int nI){
numInput = nI;
names = new String[nI];
for(int index = 0; index < nI; index++){
names[index] = fullName[index];
}
}
public String[] getList(){
return names;
}
public int getNumStudents(){
return numInput;
}
}
This is where I setup the values that will be passed on from the PracticeOne class, and later on, I will return that value back for display in PracticeOne Class.
Here is the PracticeOne Class(This is where the main method is located):
import java.util.Scanner;
public class PracticeOne {
public static void main(String[]args){
Scanner hold = new Scanner(System.in);
int menuNumChoice;
String response;
do{
System.out.println("******CONSOLE BASED STUDENT SYSTEM******");
System.out.println("1. Input Student Name");
System.out.println("2. List of Students");
System.out.print("Enter the number of choice: ");
menuNumChoice = hold.nextInt();
switch(menuNumChoice){
case 1:
inputStudentName(hold);
break;
case 2:
listStudents();
break;
default:
System.out.println("ERROR 101");
break;
}
System.out.print("Do you wish to proceed?(y/n): ");
response = hold.nextLine();
}while(response.equalsIgnoreCase("y"));
}
public static void inputStudentName(Scanner hold){
int numInput;
System.out.print("Enter number of students to input: ");
numInput = hold.nextInt();
hold.nextLine();
String[] fullName = new String[numInput];
for(int x = 0; x < numInput; x++){
System.out.println("***************************");
System.out.println("Student No. " + (x + 1));
System.out.print("Enter full name: ");
fullName[x] = hold.nextLine();
System.out.println();
}
Student s = new Student(fullName,numInput);
}
public static void listStudents(){
Student s = new Student();
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
}
Firstly I called an instance of Student in inputStudentName() method, which passes an argument for the fullname and the number of arrays being used, and tries to transfer it to Student class constructor, to get the values from there later on.
In the listStudents method, I tried displaying it by calling the getList() method from Student class to supposedly get back the names that was inputted earlier but everything was NULL. I also tried getting back the number of arrays through the getNumStudents() method but it also failed.
Kindly share some advice on how to work around with this problem or if theres a better way, suggest new things to achieve my goal.
public static void listStudents(){
**Student s = new Student();**
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
This is your listStudents logic. Instead of using the data you already created, you just create a new instance of Student. It's quite normal that this doesn't contain any information.
In your input method, you also only save the data in a local variable. This means, that once the method is finished, the data is lost.
Add a static List<Student> students = new ArrayList<>(); to your class. At the end of each input method, add the Student object to this list.
In listStudents, don't create a local student, but print the ones you stored in this List.
Based on your current system,first you can create a global variable Student[] or List then at the end of ' input Student Name()' method to save your dat.
Another Way you can use database to save your data,But this is not necessary for your system.

How would I store a list of entries after each iteration of this Java class?

This class is part of a larger application that will take a number of variables from the user, and expect to use them later, even after this particular class is left.
How can I grab the data that this class takes (after multiple iterations), and call it back from a different section?
public class A8AirlineAircraftData {
public static void AddAirline(){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the Airline name: ");
String airName = sc.nextLine();
System.out.println("Please enter the Airline code: ");
String airCode = sc.nextLine();
System.out.println("Please enter the Delta Aircraft: ");
String airCraft = sc.nextLine();
System.out.println("Please enter the first class seat capacity: ");
int firstClass = sc.nextInt();
System.out.println("Please enter the business class seat capacity: ");
int busiClass = sc.nextInt();
System.out.println("Please enter the economy class seat capacity: ");
int econClass = sc.nextInt();
System.out.println("Airline name: " + airName);
System.out.println("Airline code: " + airCode);
System.out.println("Delta Aircraft: " + airCraft);
String arr[] = airCraft.split(" ", 2);
String firstWord = arr[0];
System.out.println(firstWord + " first class seat capacity: " + firstClass);
System.out.println(firstWord + " business class seat capacity: " + busiClass);
System.out.println(firstWord + " economy class seat capacity: " + econClass);
System.out.println( airName + " successfully added. Press Enter to continue.");
sc.nextLine();//Press Enter to continue
sc.nextLine();
A8MainMenu.mainMenu(); //return to main menu after Enter.
} //AddAirline
My output now:
Airline name: Qatar Airlines
Airline code: QA
Delta Aircraft: Boeing 787 Dreamliner
Boeing first class seat capacity: 16
Boeing business class seat capacity: 25
Boeing economy class seat capacity: 199
Qatar Airlines successfully added. Press Enter to continue.
I need to just store this information somewhere in memory until I can call it later.
First create a Airline class
public class Airline {
private String name;
private String code;
// ..... other fields
public Airline(String name, String code /* , .... other parameters */) {
this.name = name;
this.code = code;
// .... other set fields
}
// getters and setters...
// equals and hashCode...
}
Next your UI (user interface) code should
should get a Scanner object as a parameter. Don't re-make a Scanner object based on System.in multiple times as that is a dangerous thing to do as you risk corrupting the System.in if you close this object early. Make it once and use it throughout.
The method should create and return an Airline object,
This method should have one responsibility and that is to get data from the user and use it to create an Airline object, nothing less and nothing more. It should not make calls to show the menu, otherwise known as "side effects" -- that's the calling code's responsibility, meaning the code that calls this method will then get the Airline object from the method, and the calling code will decide what should next be done.
e.g.,
// use a Scanner parameter
public static Airline AddAirline(Scanner sc) {
// don't re-create the Scanner object
// Scanner sc = new Scanner(System.in);
System.out.println("Please enter the Airline name: ");
String airName = sc.nextLine();
System.out.println("Please enter the Airline code: ");
String airCode = sc.nextLine();
// ..... other code
// create your Airline object
Airline airline = new Airline(airName, airCode); // plus other parameters in the complete class
return airline; // and return it
// !! the code below should be part of the calling code
// System.out.println(airName + " successfully added. Press Enter to continue.");
// sc.nextLine();// Press Enter to continue
// sc.nextLine();
// !! A8MainMenu.mainMenu(); // NO!! Don't do this
}
Define a class
Create a class to represent each airplane.
Learn about constructors.
Rough code, untested…
public class Airplane {
private String airlineName, airlineCode ;
private Integer seatCapacityFirstClass ;
// Constructor
public Airplane( String airlineNameArg , String airlineCodeArg , Integer seatCapacityFirstClassArg ) {
this.airlineName = airlineNameArg ;
this.airlineCode = airlineCodeArg ;
this.seatCapacityFirstClass = seatCapacityFirstClassArg ;
}
}
Instantiate these objects after collecting input.
Airplane a = new Airplane ( "United" , "42X937" , 42 ) ;
Make a list
Put each instance of Airplane into a collection.
List<Airplane> airplanes = new ArrayList<>() ;
airplanes.add( a ) ;
To retrieve data, add some “getter” methods to your class. Loop the list, and on each object from the list, call the getter method. For debugging, consider overriding the Object::toString method in your class to generate descriptive piece of text. All of this is covered in the Oracle Java Tutorials, and discussed in many many many Stack Overflow Questions and Answers. DuckDuckGo/Google/Bing is your friend and tutor.

I don't exactly know how .equalsIgnoreCase work?

I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.

Why is this method called twice?

I'm currently doing a fairly simple project for my class, but I encounter this weird problem.
Here's the code:
import java.util.Scanner;
public class StudentMain {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program allows you to organize a student's info in a clear, coherent form");
System.out.println("Press [1] to continue");
int x = kb.nextInt();
if (x==1){
Name();
ID();
String IDen = ID();
String name = Name();
System.out.println(name);
System.out.println(IDen);
}
}
private static String Name(){
String SName;
System.out.println("Enter Student name: ");
SName = kb.nextLine();
return SName;
}
private static String ID(){
String Sid;
System.out.println("Enter Student I.D: ");
Sid = kb.nextLine();
return Sid;
}
}
My intention for the program is listed in print statements above, but this is my biggest concern right now.
Whenever I run the program: I get this result (using it in Eclipse):
This program allows you to organize a student's info in a clear, coherent form
Press [1] to continue
1
Enter Student name:
Enter Student I.D:
John
Enter Student I.D:
1034172
Enter Student name:
John
John
1034172
As you can see, I used "John" and "1034172" as just examples, but its executing the two return methods twice. Any insight on this? All replies are welcome and greatly appreciated. Thanks!
Because you are calling it twice as result of first method calls has not been used so those are not needed.
Name();//<-------------(1)
ID();//<-------------(1)
//You can remove these lines
String IDen = ID();//<-------------(2)
String name = Name();//<-------------(2)
Note:You should follow the naming conventions as method name/variable name(except constant) should start with small case.
Here Name(); is method call and it's upto you whether you use the returned value or not.
Name();//First Call
String name =Name();//Second Call

BirthDay Wizard Program

Given a person’s age, build a Birthday Wizard that can compute the year of birth, considering that you ask the person's age today. Write statements that can be used in a Java program to perform this computation for the Birthday Wizard.
Here what I needed up but it doesn't work. could someone point what I am doing wrong :
import java.util.Scanner;
public class Birthday
{
public static void main(String[]args)
{
int birthday;
int age;
int YearOfBirth;
Scanner keyboard = new Scanner( System.in);
System.out.println(" What is your +Age ?");
age = keyboard.nextInt();
YearOfBirth= 2011 - age;
System.out.println("I was born :+ YearsOfBirth.");
}
}
System.out.println("I was born :+ YearsOfBirth.");
You never close your quote before showing yearsOfBirth
System.out.println("I was born : "+ YearsOfBirth+".");
Try that and let me know.
Also I just noticed you variable names are wrong: in the print statement its YearsOfBirth when you declare it it's YearOfbirth.
System.out.println("I was born :+ YearsOfBirth.");
Should be
System.out.println("I was born :" + YearOfBirth + ".");
Don't know if the age = keyboard.nextInt(); will work though.
System.out.println("I was born :+ YearsOfBirth."); ......this is wrong
use this :
System.out.println("I was born :+" YearsOfBirth);
System.out.println("I was born :+ YearsOfBirth.");
This results in the String literal "I was born :+ YearsOfBirth." being printed out. It's not quite what you want. Perhaps this, is what you meant:
System.out.println("I was born :"+ YearsOfBirth);
This time, the variable YearsOfBirth is converted to a String and concatenated with "I was born :" to provide the desired result.
In Java, when ever you apply the concatenation operator (+) on two objects, and one of them happens to be a String, then the other will be converted to a String object (the value might not make sense), and a new String object will be returned. Also, literals in double-quotes are often Strings.
import java.util.Scanner;
public class Birthday
{
public static void main(String[]args)
{
int birthday;
int age;
int yearOfBirth;
System.out.println(" What is your Age ?");
Scanner keyboard = new Scanner( System.in);
String input = keyboard.nextLine();
age = Integer.parseInt(input);
yearOfBirth = 2011 - age;
System.out.println("I was born :" + yearOfBirth);
}
}
This should work.

Categories

Resources