how to use a do-while loop in a class? - java

how would I create a do-while loop to verify that the user input contains no special characters. If it does contain special characters, how would I make it restart the loop? In my loop, it still returns the name if it has special characters.
Here is my main:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
System.out.print("Enter first and last name: ");
String userName = input.nextLine();
user.setName(userName);
user.getName();
}
}
Here is my User class:
import java.util.Random;
public class UserInterface {
Random random = new Random();
private String name;
public String getName() {
String specialCharacters = "!#$%&'()*+,-./:;<=>?#[]^_`{|}123456789";
boolean invalidInput = false;
do {
invalidInput = false;
System.out.print("User: " + name + " ID #" + getUserID());
} while(name.contains(specialCharacters));
invalidInput = false;
return name;
}
public void setName(String userName) {
this.name = userName;
}
public int getUserID() {
return random.nextInt(1000);
}
}

use do while loop to verify weather the user name is valid or not.
For validating use:
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
For getting name:
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
Main.java
import java.util.Random;
import java.util.Scanner;
class UserInterface {
Random random = new Random();
private String name;
public void setName(String userName) {
this.name = userName;
}
public String getName(){
return name;
}
public int getUserID() {
return random.nextInt(1000);
}
}
public class Main {
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
user.setName(inputName());
System.out.println(user.getName());
}
}
Output:
$ javac Main.java && java Main
Enter Name : Dev Par
Enter Name : DevPar
DevPar

Related

How can i verify if i'm adding atributes to a list that are equal?

import entidades.*;
public class Main {
public static void main(String[] args) {
Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop == true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.nextLine();
String categoriaPro = sc.nextLine();
prof.NomeVerificacao(profissional, nomePro, categoriaPro);
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissional) {
System.out.println(pro);
This is my Main, it's running fine but i don´t think it is adding the atributes to the list and not verifying either.
i want to add the atributes to a list so i can create different objets but they can not have at least the name equal.
public class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
public void NomeVerificacao(List<Profissional> profissional ,String nome, String categoria) {
if(profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
}else {
for(Profissional pro : profissional) {
if(pro.nome.contentEquals(nome)) {
System.out.println("Já Exite esse nome");
}else {
profissional.add(new Profissional(nome, categoria));
}
}
}
}
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
this is the Profissional Class.
I'm almost there i think but the output keeps saying that the name exists even though it is the first name i'm inserting.
I ran your code on my machine and made 3 changes into it, and it's working for me now,
1)
String nomePro = sc.next();
String categoriaPro = sc.next();
2) In professional class just changed this function a bit:
public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
if (profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
} else {
int i = 0;
for (; i < profissional.size(); i++) {
if (profissional.get(i).nome.equals(nome)) {
System.out.println("Já Exite esse nome");
break;
}
}
if (i == profissional.size()) {
profissional.add(new Profissional(nome, categoria));
}
}
}
3) At the end of the class Main, wrote sc.close(); to close the scanner.
i/p and o/p :
1) RP
red
color
2) RP
orange
color
3) RP
orange
paint
Já Exite esse nome
4) SAIR
nome=red, categoria=color
nome=orange, categoria=color
As you can see in above i/p and o/p, nome=red and nome=orange with categoria=color are added in the list but when we tried to add the same nome=orange again but with different category as paint it didn't add it and printed the message "Já Exite esse nome".
and after entering SAIR, the toString(); printed the list content at the end. So the message will be printed only if we try to add the object with the same name again int list (not the first or any other times).
Further optimizations are possible but for now, it will work!
I can propose the following solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Set is a data structure that makes sure you don't have a duplicated elements
// in this case we use TreeSet structure that accepts comparator which tells that
// we need to compare elements only by professional's name
Set<Profissional> profissionals = new TreeSet<>(Comparator.comparing(Profissional::getNome));
while (true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.next();
String categoriaPro = sc.next();
// add function returns true in case the element we're going to add
// was not presented in Set structure yet. False otherwise.
boolean isNew = profissionals.add(new Profissional(nomePro, categoriaPro));
if (!isNew) {
System.out.println("Professional with name " + nomePro + " already exists");
} else {
System.out.println("Professional with name " + nomePro + " was added");
}
} else if (comando.contentEquals("SAIR")) {
break;
}
}
// just prints all professionals at the end of the program
profissionals.forEach(System.out::println);
}
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
// getters and setters
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
The output will be the following:
RP
test test
Professional with name test was added
RP
test1 test1
Professional with name test1 was added
RP
test test3
Professional with name test already exists
SAIR
nome=test, categoria=test
nome=test1, categoria=test1
package javaapplication8;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JavaApplication8 {
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
}
public static void main(String[] args) {
try {
List<Profissional> profissionalList= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\r\nEnter comando:");
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
System.out.print("nome: ");
String nome = sc.next();
sc.nextLine(); // wait enter
System.out.print("categoria: ");
String categoria = sc.next();
sc.nextLine(); // wait enter
// access constructor of Profissional
Constructor profCtor = Profissional.class.getConstructor(String.class, String.class);
profCtor.setAccessible(true);
// create instance of Profissional
Profissional newItem = (Profissional) profCtor.newInstance(nome, categoria);
// avoid duplicate nome in profissionalList
boolean isExist = false;
for(Profissional pro : profissionalList) {
if(pro != null){
if(pro.nome.toLowerCase().equals(newItem.nome.toLowerCase())){
isExist = true;
break;
}
}
}
if(!isExist){
profissionalList.add(newItem );
}
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissionalList) {
if(pro != null) {
System.out.println("nome: " + pro.nome + " categoria: " + pro.categoria);
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

array in object oriented programming

I'm a beginner in object-oriented programming and this is my first little project.I've heard that here everyone can help you in your code and this is my first time.Anyway, my problem why array doesn't store any value?
Here is the code:
public class Information {
private IT_Members[] member= new IT_Members[10];
private int counter = 0;
Information()
{
for ( int ctr=0;ctr<member.length;ctr++)
{
member[ctr] = new IT_Members ();
}
}
public void Add(IT_Members member)
{
if(counter<10)
{
this.member[counter].setName(member.getName());
this.member[counter].setDeparment(member.getDeparment());
this.member[counter].setPostion(member.getPostion());
this.member[counter].setID(member.getID()+counter);
counter++;
}
else
System.out.println("Add List Full");
}
public void Display()
{
if (counter!=0)
{
for (int ctr=0;ctr<10;ctr++){
System.out.println(this.member[ctr].getName()+
this.member[ctr].getDeparment()+
this.member[ctr].getPostion()+
this.member[ctr].getID());
}
}
else
System.out.println("No member yet!");
}
Here is the Main class:
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
IT_Members input1 = new IT_Members();
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
.........................................................................
public class IT_Members {
private String name,deparment,postion;
private int ID=1000;
private int Flag=0;
IT_Members (){
}
IT_Members (String name, String deparment , String postion ,int ID , int Flag){
this.name= name;
this.deparment=deparment;
this.postion=postion;
this.ID=ID;
this.Flag=Flag;
}
public String getName (){
return this.name;
}
public String getDeparment (){
return this.deparment;
}
public String getPostion (){
return this.postion;
}
public int getID (){
return this.ID;
}
public int getFlag (){
return this.Flag;
}
public void setName (String name){
this.name = name;
}
public void setDeparment (String Deparment){
this.deparment = deparment;
}
public void setPostion (String postion){
this.postion = postion;
}
public void setID (int ID){
this.ID = ID;
}
public void setFlag (int Flag){
this.Flag = Flag ;
}
public String toStu()
{
String str = "";
str = "\nName: " + this.name +
"\nDeparment: " + this.deparment +
"\nPostion: " + this.postion +
"\nID: " + this.ID;
return str;
}
}
Please, I'm stuck with this I appreciate any help.
Thanks.
You never call the Add function in the Information class. Therefore you never initialize any of the array elements you then want to display.
You need to add input2.Add(input1) before you print that is has been added.
You have to create every time a new Object and in the end you have to add in the list.
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
IT_Members input1 = new IT_Members();// this need to be here so that every time crete new object
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
input2.Add(input1); // that was missing
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}

AddressBook in Java

I have to create an address book in java. I have gotten stuck in one area. When I add a second address it makes the first one null. I have areas commented out that I haven't gotten to yet so ignore those areas. I am at a loss why the first address turns to null.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
class Program2 {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("\nWelcome. Address book is loaded.");
loop: while(true) {
displayOptions();
int choice = s.nextInt();
switch(choice) {
case 1:
System.out.println("**Choice 1**");
AddressBook.display();
break;
case 2:
System.out.println("**Choice 2**");
System.out.print("First Name: ");
String firstName = s.next();
System.out.print("Last Name: ");
String lastName = s.next();
System.out.print("Phone Number: ");
String phone = s.next();
Contact test = new Contact(firstName, lastName, phone);
AddressBook.add(test);
break;
case 3:
System.out.println("**Choice 3**");
break;
case 4:
System.out.println("**Choice 4**");
break;
case 5:
break loop;
}
}
System.out.println("\nAddress book is saved to file.\n");
System.out.println("Good bye.\n");
System.exit(0);
}
private static void displayOptions() {
System.out.println("\nWhat would you like to do?");
System.out.println(" 1) Display all contacts\n" +
" 2) Add a contact\n" +
" 3) Remove a contact\n" +
" 4) Search a contact\n" +
" 5) Exit");
System.out.print("Your choice: ");
}
}
class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getPhone() {return phone;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public void setPhone(String phone) {this.phone = phone;}
/*public boolean equals(Object o) {
if (o instanceof Contact) {
Contact contacts = (Contact) o;
return (firstName.equals(contacts.getFirstName()) &&
lastName.equals(contacts.getLastName()));
}
return false;
}*/
public String toString() {
return firstName + " " + lastName + "\t\t" + phone;
}
}
class AddressBook {
public final static int CAPACITY = 100;
static private Contact[] contacts;
static private int count = 0;
static private String addressFile = "address.txt";
static File file = new File(addressFile);
public AddressBook(String addressFile) {
this.addressFile = addressFile;
}
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY];
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
//public boolean remove(fullname) { }
//public Contact search(fullname) { }
public static void display() {
System.out.println("Name\t\t\tPhone Number");
System.out.println("-------------------------------------");
for (int i=0; i<count; i++) {
System.out.println(contacts[i]);
}
System.out.println("-------------------------------------");
}
/*public boolean load() {
try {
Scanner sF = new Scanner(file);
while (s.hasNext()) {
String line = s.nextLine();
System.out.println(line);
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*public boolean save() {
try {
FileWriter writer = new FileWriter(addressFile);
writer.write();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
//public boolean contains(String firstName, String lastName) {
// return this.contacts.contains(firstName, lastName);
//}
}
Your add method overwrites the contacts array, so each time it is called, the references to the previous Contacts are lost :
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY]; // remove this line
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
Instead of the removed line, initialize the contacts array only once :
static private Contact[] contacts = new Contact[CAPACITY];

Printing string arrays to a text file using java

I am trying to print out the results of the users inputs to a simple text file but everything I have tried has rendered unsuccessful. I tried using a PrintWriter within the switch case but the results still just printed out null. I am quite new to Java so maybe I am missing obvious?
Here is the code:
package parkingsystem;
import java.io.*;
import java.util.Scanner;
public class Registration {
static String [][] userData;
static String [][] fileData;
public static void Registration(){
Scanner input = new Scanner(System.in);
String lotNo;
String First;
String Last;
String studentID;
String phoneNo;
String email;
String carNo;
String dateReg;
String strcontent;
String proceed;
boolean proceed2 = true;
userData = new String [50][6];
fileData = new String [50][6];
int counter = 0;
int col;
int row;
boolean carry_on = true;
MainMenu choices = new MainMenu();
while(proceed2=true){
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
proceed = input.nextLine();
switch (proceed) {
case "Y":
case "y":
System.out.println("Enter your student ID");
studentID = input.nextLine();
System.out.println("Enter your first name");
First = input.nextLine();
System.out.println("Enter your last name");
Last = input.nextLine();
System.out.println("Enter your car number");
carNo = input.nextLine();
System.out.println("Enter your contact number");
phoneNo = input.nextLine();
System.out.println("Enter your email address");
email = input.nextLine();
row = counter ;
userData [row][0] = studentID;
userData [row][1] = First;
userData [row][2] = Last;
userData [row][3] = carNo;
userData [row][4] = phoneNo;
userData [row][5] = email;
if (counter == 6){
carry_on=false;
}
proceed2 = false;
break;
case "N":
case "n":
choices.Menus();
break;
}
}
}
}
Here's a second pass at re-factoring your code.
So now in this refactoring we capture and store the newly created CarOwner objects and store them in a list.
Then we see how to go through that List of CarOwner's and then write those objects to a file called carOwners.dat
Ordinarily, in industry, code re-factoring is done in the context of having a set of unit tests against which you can ensure that the refactoring hasn't broken the required behaviour of the code but we are just learning here so this work serves to explain some of the concepts that you are missing and this first pass iteration below has some issues of its own so don't take this as the final product.
Refactorings
I have created a CarOwner class.
I have renamed the Boolean variable canProceed so that it reads more naturally.
Update : I have made the CarOwner class Serializable; this will allow us to write the Object to a File.
Update : I have added code that up the new CarOwners and adds it to a List and then I iterate over the list to write those CarOwner objects to a FileStream.
package parkingsystem;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.FileOutputStream;
import java.util.Scanner;
public class Registration {
public static void main(String[] args) {
List carOwners = new ArrayList();
Scanner input = new Scanner(System.in);
boolean canProceed = true;
while (canProceed) {
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
String optionRequested = input.nextLine();
if (optionRequested.equalsIgnoreCase("Y")) {
CarOwner owner = new CarOwner();
System.out.println("Enter your student ID");
owner.setStudentID(input.nextLine());
System.out.println("Enter your first name");
owner.setFirst(input.nextLine());
System.out.println("Enter your last name");
owner.setLast(input.nextLine());
System.out.println("Enter your car number");
owner.setCarNo(input.nextLine());
System.out.println("Enter your contact number");
owner.setContactNumber(input.nextLine());
System.out.println("Enter your email address");
owner.setEmail(input.nextLine());
owner.setDateReg(new Date().toString());
carOwners.add(owner);
} else if (optionRequested.equals("N") || optionRequested.equals("n")) {
canProceed = false;
}
}
ObjectOutputStream objectWriter = null;
for (CarOwner carOwner : carOwners) {
try {
objectWriter = new ObjectOutputStream(new FileOutputStream("carOwners.dat"));
objectWriter.writeObject(carOwner);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's what the CarOwner class now looks like ...
package parkingsystem;
import java.io.Serializable;
public class CarOwner implements Serializable{
private String First;
private String Last;
private String studentID;
private String email;
private String carNo;
private String dateReg;
private String contactNumber;
public CarOwner() {
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getDateReg() {
return dateReg;
}
public void setDateReg(String dateReg) {
this.dateReg = dateReg;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactNumber() {
return contactNumber;
}
#Override
public String toString() {
return "CarOwner{" +
"First='" + First + '\'' +
", Last='" + Last + '\'' +
", studentID='" + studentID + '\'' +
", email='" + email + '\'' +
", carNo='" + carNo + '\'' +
", dateReg='" + dateReg + '\'' +
", contactNumber='" + contactNumber + '\'' +
'}';
}
}
Ok so creating the CarOwner class is done to make a start at making this code more object oriented.
Secondly the re-factored code demonstrates correct use of a Boolean variable in Java.
As the other commentators have already pointed out the assignment operator = is easily confused with the test for Boolean equality. See Java Operators
Also I have renamed Boolean proceed; to be Boolean canProceed; This is a common strategy. Naming a Boolean variable to read as a question to which the "answer" is, yes or no, or True or False.
This then means we can write code like while(canProceed) which reads very easily. See also if statement on the Java tutorial
I hope this helps.

JAVA Linked List Confused on why I can't check a variable against an node in the Linked List?

public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) { //WHY IS THIS ASKING FOR SEPARATE METHOD?
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
I am trying to take an input and check to see if that input is in the Linked List. I am having problems though getting this to work right.
If I add the new method in my LinkedList.Java class it says it needs to define a variable for link. Below is what I have in entirety if it helps:
import java.util.Scanner;
class airline {
public static LinkedList list = new LinkedList();
public static void main(String[] args) {
list.addAirplane("Allen",501);
list.addAirplane("James",501);
list.addAirplane("Andrea",501);
list.addAirplane("Velvett",501);
list.addAirplane("Paul",501);
//Method sort the list after year the car was made
list.sortList();
menu();
//Method to print all objects in List
System.out.println(list.viewAll());
}
public static void menu(){
int menuOpt;
System.out.println("Airline Menu:");
System.out.println("1. Reserve a Ticket");
System.out.println("2. Cancel Reservations");
System.out.println("3. Check Reservations");
System.out.println("4. Display Airplanes on Flights");
Scanner input = new Scanner(System.in);
menuOpt=input.nextInt();
System.out.println(menuOpt);
switch (menuOpt){
case 1:
System.out.println("Reserve a Ticket");
reserveTick();
break;
case 2:
System.out.println("Cancel Reservations");
cancel();
break;
case 3:
System.out.println("Check Reservations");
check();
break;
case 4:
System.out.println("Passengers listed by Flights");
break;
default:
System.out.println("INVALID RESPONSE!");
menu();
break;
}
}
public static void reserveTick(){
String name;
System.out.println("Enter Customer Name to RESERVE ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.addAirplane(name,501);
System.out.println(name + " has been added to Flight Number 501");
menu();
}
public static void cancel(){
String name;
System.out.println("Enter Customer Name to CANCEL ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.remove(name, 501);
System.out.println(name + " has been REMOVED from Flight Number 501");
menu();
}
public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) {
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
else {
System.out.println(name + " is not on this Flight!");
menu();
}
}
public static void listpassengers(){
list.sortList();
}
}
------------------------------------------------------------------
import java.util.*;
public class LinkedList
{
private AirplaneNode head = null;
public void addAirplane(String name , int hk)
{
//If head = null then create the first node
if(head == null)
{
head = new AirplaneNode(name,hk,null);
}
else
{
//If there are more than 1 node
head = new AirplaneNode(name,hk,head);
}
}
public void sortList()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(AirplaneNode cursor = head ; cursor.getNext() != null ; cursor = cursor.getNext())
{
if(cursor.getHk() < cursor.getNext().getHk())
{
String n = cursor.getName();
int hk = cursor.getHk();
cursor.setName(cursor.getNext().getName());
cursor.setHk(cursor.getNext().getHk());
cursor.getNext().setName(n);
cursor.getNext().setHk(hk);
sorted = false;
}
}
}
}
public String viewAll()
{
StringBuffer str = new StringBuffer();
for(AirplaneNode cursor = head ; cursor != null ; cursor = cursor.getNext())
{
str.append(cursor+"\n");
}
return new String(str);
}
}
--------------------------------------------------------------
public class AirplaneNode
{
private String name;
private int hk;
private AirplaneNode next;
public AirplaneNode(String name,int hk,AirplaneNode head)
{
this.name = name;
this.hk = hk;
this.next = head;
}
public AirplaneNode getNext()
{
return next;
}
public String getName()
{
return name;
}
public int getHk()
{
return hk;
}
public void setName(String in)
{
name = in;
}
public void setHk(int in)
{
hk = in;
}
public String toString()
{
return name + " " + hk ;
}
}
It seems as if you are creating a own class LinkedList in the top package here:
import java.util.*;
public class LinkedList
{
Since your method check() belongs in the airline class in the same package (and without any import of java.util.LinkedList) it will instead use the class you have created and that class doesn't implement any contains() method.
Declare your linked list this way:
public static LinkedList<String> list = new LinkedList<String>();
EDIT (based on your comment):
It looks like you want a list of flights, where each flight has a list of passenger names.
public class Flight implements Comparable<Flight> {
private List<String> mPassengers;
private final int mFlight;
private static final Collator sCollator = Collator.getInstance();
public Flight(int flight) {
mPassengers = new ArrayList<String>();
mFlight = flight;
}
public void sortPassengers() {
Collections.sort(mPassengers, sCollator);
}
public void addPassenger(String name) {
mPassengers.add(name);
}
public boolean removePassenger(String name) {
return mPassengers.remove(name);
}
public boolean hasPassenger(String name) {
return mPassengers.contains(name);
}
public String getFlight() { return mFlight; }
public int compareTo(Flight other) {
return mFlight - other.mFlight;
}
}
public static List<Flight> list = new LinkedList<Flight>();
public static void main(String[] args) {
Flight flight = new Flight(501);
flight.addPassenger("Allen");
// etc. for all flight 501 passengers
list.add(flight);
// repeat all the above for each flight number
}
You should be able to fill in the rest.

Categories