How do i clear screen? - java

After user enter Status and enter how can i make everything on the top disappear and just show whatever's below that. I do want the inputs to be visible anymore. How can i implement this? Can someone help me fix my code, I previously tried a system out flush but it did not work. Thank you very much.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Car> cars = new ArrayList<>();
int choice;
Car car = new Car();
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("\n1 - Insert car\n2 - Edit car\n3 - Exit");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
switch (choice){
case 1:
car = new Car();
scanner = new Scanner(System.in);
System.out.println("Enter Plate number: ");
car.setPlateNumber(scanner.nextLine());
System.out.println("Enter Brand: ");
car.setBrand(scanner.nextLine());
System.out.println("Enter Model: ");
car.setModel(scanner.nextLine());
System.out.println("Enter type: ");
car.setType(scanner.nextLine());
System.out.println("Enter Color: ");
car.setColour(scanner.nextLine());
System.out.println("Enter Price: ");
car.setPrice(scanner.nextDouble());
scanner = new Scanner(System.in);
System.out.println("Enter Status: ");
car.setStatus(scanner.nextLine());
cars.add(car);
System.out.println("\nCar saved successfully!!");
break;
case 2:
car = new Car();
scanner = new Scanner(System.in);
System.out.println("Enter car Plate Number: ");
car.setPlateNumber(scanner.nextLine());
if(!car.editCarRecord(cars))
System.out.println("Car not found!!");
break;
case 3:
return;
default:
System.out.println("Invalid option!!");
}
}
}
}
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Car {
private String plateNumber;
private String brand;
private String model;
private String type;
private String colour;
private String status;
private double price;
public Car() {
// Define this if we want default values
}
public Car(String pn, String br, String mo, String ty, String co, String st, double pr) {
plateNumber = pn;
brand = br;
model = mo;
type = ty;
colour = co;
status = st;
price = pr;
}
public void setPlateNumber(String pn) {
plateNumber = pn;
}
public void setBrand(String br) {
brand = br;
}
public void setModel(String mo) {
model = mo;
}
public void setType(String ty) {
type = ty;
}
public void setColour(String co) {
colour = co;
}
public void setStatus(String st) {
status = st;
}
public void setPrice(double pr) {
price = pr;
}
public String getPlateNumber() {
return plateNumber;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public String getType() {
return type;
}
public String getColour() {
return colour;
}
public String getStatus() {
return status;
}
public double getPrice() {
return price;
}
public boolean editCarRecord(ArrayList<Car> list){
Scanner scanner = new Scanner(System.in);
int choice;
for(int i=0; i<list.size(); i++) {
if (list.get(i).getPlateNumber().compareToIgnoreCase(this.getPlateNumber()) == 0) {
System.out.println("Car record matched!!");
System.out.println(list.get(i).toString());
while(true) {
System.out.println("1 - Edit Status\n2 - Edit Price\n3 - Edit Color\n4 - Back to main menu");
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
if (choice == 1) {
System.out.println("Enter new Status: ");
list.get(i).setStatus(scanner.nextLine());
System.out.println("Status updated Successfully!");
} else if (choice == 2) {
System.out.println("Enter new Price: ");
list.get(i).setPrice(scanner.nextDouble());
System.out.println("Price updated Successfully!");
} else if (choice == 3) {
System.out.println("Enter new Color: ");
list.get(i).setColour(scanner.nextLine());
System.out.println("Color updated Successfully!");
} else if (choice == 4) {
return true;
} else {
System.out.println("Invalid choice!!");
}
}
}
}
return false;
}
public String toString() {
return "Plate number: " + plateNumber
+ "\nBrand: " + brand
+ "\nModel: " + model
+ "\nType: " + type
+ "\nColour: " + colour
+ "\nStatus: " + status
+ "\nPrice: " + price;
}
}

Related

Difficulty setting and updating objects in a Sorted ArrayList [duplicate]

This question already has answers here:
method in class cannot be applied to given types
(7 answers)
Closed 2 years ago.
I wish to be able to update information about objects entered by a user. I would like the user to enter a book name and user name to take out the book, as well as being able to return it with the same information. The objects have to be inserted into the right place in my sortedarraylists. Each user is assumed to be unique and each book can only be taken out by one user (who can take out up to 3 books).
When I try to compile my code, I get this error message:
java: method issueBook in class Driver cannot be applied to given types;
required: Book,User
found: no arguments
reason: actual and formal argument lists differ in length
This corresponds to issueBook(); in case i of my menu.
I also have User and Book classes that implement Comparable<Book> etc. I tried to omit as much irrelevant code as I could, such as the filereader to scan in new user and book objects. I included the book and user classes in case they need to be looked at (I think they are mostly fine). Please let me know if you need any more details however.
import java.io.*;
import java.util.Scanner;
public class Driver {
static Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------------------\n"+
"f: Finish running the program\n" +
"b -Display on the screen the information about all the books in the library\n" +
"u -Display on the screen the information about all the users.\n" +
"i -Update the stored data when a book is issued to a user\n" +
"r -Update the stored data when a user returns a book to the library\n" +
"------------------------------\n" +
"Type a letter and press Enter\n");
}
private static User readNames() throws User.InvalidBookLimitException {
System.out.println("Enter the user's firstname: ");
String firstName = sc.next();
System.out.println("Enter the user's surname: ");
String surName = sc.next();
sc.nextLine(); //TODO check this
return new User(firstName, surName, 0);
}
private static User readUserData(User user) throws User.InvalidBookLimitException {
User u = readNames();
System.out.println("Enter " + user + "'s age, and press Enter");
int numberOfBooks = sc.nextInt();
sc.nextLine();
return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
}
private static Book readBookName (){
System.out.println("Type in the name of the book");
String bookName = sc.nextLine();
return new Book(bookName);
}
/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>(); public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.
public void issueBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(true);
/*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1);
}
}
}
public void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(false);
b.setLoanerNames(null, null);
break;
} for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
}
}
}
}
public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
//These SortedArrayLists have been derived from the sorted arraylist class
SortedArrayList<User> sortedUsers = new SortedArrayList<>();
SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
/*for (Object item : sortedBooks) {
System.out.println(sortedBooks.toString());
}*/
System.out.println(sortedBooks/*.toString()*/);
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers/*.toString()*/);
break;
case 'i':
System.out.println("Enter the loaning out data. ");
System.out.println("Enter the user's first name and surname: ");
readNames();
System.out.println("Enter the name of the book: ");
readBookName();
issueBook();
or maybe if(u1.compareTo(u2) == 0)*/
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
/*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work
/*returnBook(b);*/
break;
default:
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
My sorted arraylist class with a (working) insert method:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//no need for a generic in the insert method as this has been declared in the class
public void insert(E value) {
if (this.size() == 0) {
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i));
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0) {
return; }
}
this.add(value);
}
User class:
import java.io.PrintWriter;
public class User implements Comparable<User> {
private String firstName;
private String surName;
private int numberOfBooks;
public User(){
firstName = "";
surName = "";
numberOfBooks = 0;
}
public class InvalidBookLimitException extends Exception{
public InvalidBookLimitException(){
super("Invalid number of books");
}
}
public User(String name1, String name2, int books) throws InvalidBookLimitException {
this.firstName = name1;
this.surName = name2;
if (books>3) throw new InvalidBookLimitException ();
this.numberOfBooks = books;
}
public String getFirstName() {
return firstName;
}
public String getSurName(){
return surName;
}
public int getNumberOfBooks(){
return numberOfBooks;
}
public boolean borrowMoreBooks(){
return numberOfBooks < 3;
}
public void setNumberOfBooks(int numberOfBooks){
this.numberOfBooks=numberOfBooks;
}
public void setUser(String name1, String name2, int books){
firstName = name1;
surName = name2;
numberOfBooks = books;
}
public boolean userNameTest (User otherUser){
return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
}
/* public boolean loanAnotherBook(){
return !(numberOfBooks<3);
numberOfBooks++;
}*/
public void printName(PrintWriter f){f.println(firstName+ " " + surName);}
/*
public void setUser(User user) {
if (loanStatus == false){
loanStatus = Driver.readNameInput();
loanStatus = true;
}
}*/
#Override
public String toString(){
return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
}
public int compareTo(User u) {
/* int snCmp = surName.compareTo(u.surName);
if (snCmp != 0)
return snCmp;
else{
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp !=0)
return fnCmp;
}*/
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp != 0) return fnCmp;
int snCmp= surName.compareTo(u.surName);
if (snCmp !=0) return snCmp;
else return numberOfBooks -u.numberOfBooks;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Book class:
public class Book implements Comparable<Book>{
public String bookName;
public String authorName;
public boolean loanStatus;
public String loanerFirstName;
public String loanerSurName;
//if boolean loanStatus == true private string loaner name
public Book(){
bookName = "";
authorName = "";
loanStatus = false;
loanerFirstName = null;
loanerSurName = null;
}
Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {
this.bookName = book;
this.authorName = author;
this.loanStatus = loanStatus;
this.loanerFirstName = loanerFirstName;
this.loanerSurName = loanerSurName;
}
Book(String book){
this.bookName=book;
}
public String getBookName(){
return bookName;
}
public String getAuthorName(){
return bookName;
}
public boolean getLoanStatus(){
return loanStatus;
}
public String getLoanerFirstName(){
return loanerFirstName;
}
public String getLoanerSurName(){
return loanerSurName;
}
public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
bookName = book;
authorName = author;
loanStatus = loanStatus;
loanerFirstName = loanerFirstName;
loanerSurName = loanerSurName;
}
public void setBookName(String bookName){
this.bookName=bookName;
}
public void loanStatus(boolean loanStatus){
this.loanStatus=loanStatus;
}
public void setLoanerNames(String loanerFirstName, String loanerSurName){
this.loanerFirstName=loanerFirstName;
this.loanerSurName=loanerSurName;
}
/* public boolean nameTest (User otherUser){
return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
}
*/
public String toString(){
return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
}
//this may be redundant TODO
/* public void setLoanStatus(User user){
loanStatus = false;
}*/
//This compare method allows new user objects to be compared to ones in the
#Override //sortedArrayList, enabling the insertion method.
public int compareTo(Book b) {
int bnCmp = bookName.compareTo(b.bookName);
if (bnCmp != 0) return bnCmp;
int anCmp= authorName.compareTo(b.authorName);
if (anCmp !=0) return anCmp;
// int lsCmp= loanStatus.(b.loanStatus);
// if (lsCmp !=0) return lsCmp;
int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
if (lrfnCmp !=0) return lrfnCmp;
int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
if (lrlnCmp !=0) return lrlnCmp;
else return 0;
}
}
User user = readNames();
Book book = readBookName();
issueBook(book, user);
You have to pass the user and book which you have created while calling the issueBook method.

parking ticket sim having output issue

Truthfully, I mixed some codes.
I need output like below:
Parking ticket #:
Fined amount:
Car issued to:
Issued by officer:
But here is current output:
Fined amount:
Car issued to:
Parking ticket #:null
Fined amount:
Issued by officer:
So looks like the main issue is with generating a parking ticket #
Code is
import java.util.Scanner;
public class ParkingTicketSimulator
{
public static void main(String[] args)
{
String make, model, color, license, name, badge;
int parkedMinutes, meterMinutes;
Scanner keyboard = new Scanner(System.in);
System.out.print("=== Parking Ticket Simulator ===\n\n");
System.out.print("---------\n");
System.out.print("Car Data\n");
System.out.print("---------\n\n");
System.out.print("Enter the car make: ");
make = keyboard.nextLine();
System.out.print("Enter the car model: ");
model = keyboard.nextLine();
System.out.print("Enter the car color: ");
color = keyboard.nextLine();
System.out.print("Enter the car license number: ");
license = keyboard.nextLine();
System.out.print("Enter minutes car has been parked:");
parkedMinutes = keyboard.nextInt();
System.out.print("\n----------\n");
System.out.print("Meter Data\n");
System.out.print("----------\n\n");
System.out.print("Enter minutes purchased by driver:");
meterMinutes = keyboard.nextInt();
keyboard.nextLine();
System.out.print("\n-------\n");
System.out.print("PO Data\n");
System.out.print("-------\n\n");
System.out.println();
System.out.print("Enter police officer's name:");
name = keyboard.nextLine();
System.out.print("Enter police officer's badge number:");
badge = keyboard.nextLine();
System.out.print("\n---------------------\n");
System.out.print("Parking Ticket Issued\n");
System.out.print("---------------------\n\n");
ParkedCar car = new ParkedCar(make,model,color,license,parkedMinutes);
ParkingMeter meter1 = new ParkingMeter (meterMinutes);
PoliceOfficer officer1 = new PoliceOfficer(name,badge,car,meter1);
System.out.println(officer1.getExpired(officer1));
}
public static class ParkedCar {
private String make;
private String model;
private String color;
private String license;
private int minutesParked;
public ParkedCar() {
make = "";
model = "";
color = "";
license = "";
minutesParked = 0;
}
public ParkedCar(ParkedCar carDetails){
make = carDetails.make;
model = carDetails.model;
color = carDetails.color;
license = carDetails.license;
minutesParked = carDetails.minutesParked;
}
public ParkedCar(String make, String model, String color, String license, int minutesParked){
this.make = make;
this.model = model;
this.color = color;
this.license = license;
this.minutesParked = minutesParked;
}
public void setMake (String make){
this.make = make;
}
public void setModel (String model){
this.model = model;
}
public void setColor (String color){
this.color = color;
}
public void setLicense (String license){
this.license = license;
}
public void minutesParked (int minutesParked){
this.minutesParked = minutesParked;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public String getColor(){
return color;
}
public String getLicense(){
return license;
}
public int getMinutesParked(){
return minutesParked;
}
public String toString(){
String str = "\nMake: " + make + "\nModel: " + model + "\nColor: " + color + "\nLicense: " + license + "\nMinutes parked: " + minutesParked;
return str;
}
}
public static class ParkingMeter {
private int minutes;
public ParkingMeter() {
minutes = 0;
}
public ParkingMeter(int minutes){
this.minutes = minutes;
}
public ParkingMeter (ParkingMeter minutesDetail){
minutes = minutesDetail.minutes;
}
public void setMinutes (int minutes){
this.minutes = minutes;
}
public int getMinutes(){
return minutes;
}
public String toString(){
String str ="\nMinutes: " + minutes;
return str;
}
}
public static class ParkingTicket{
private PoliceOfficer officer; //Calls the officer details.
private ParkedCar car;
private ParkingMeter meter;
private int fees;
public ParkingTicket(PoliceOfficer officer){
this.officer = new PoliceOfficer(officer);
this.meter = officer.getMeter();
this.car = officer.getParkedCar();
}
public ParkingTicket(){
}
public int fees(){
int time;
if (car != null || meter != null){
time = car.getMinutesParked() - meter.getMinutes() - 1;
fees = 25;
while (time > 0){
time = time - 1;
fees = fees+10;
}
}
return fees;
}
public String toString(){
if (fees() == 0 ){
String str = "There is no ticket issued.";
return str;
}
else{
String str = "\n" + officer +"\nTime over: " + (car.getMinutesParked() - meter.getMinutes()) + "\nThe fee is $" + fees();
return str;
}
}
}
public static class PoliceOfficer{
private String name;
private String badge;
private ParkedCar car;
private ParkingMeter meter;
private ParkingTicket ticket;
public PoliceOfficer(String name, String badge, ParkedCar carDetails, ParkingMeter time) {
this.name = name;
this.badge = badge;
car = new ParkedCar(carDetails);
meter = new ParkingMeter(time);
}
public PoliceOfficer(PoliceOfficer officerDetails){
name = officerDetails.name;
badge = officerDetails.badge;
car = officerDetails.car;
meter = officerDetails.meter;
}
public void setName (String name){
this.name = name;
}
public void setBadge (String badge){
this.badge = badge;
}
public String getName(){
return name;
}
public String getBadge(){
return badge;
}
public ParkedCar getParkedCar() {
return new ParkedCar(car);
}
public ParkingMeter getMeter(){
return new ParkingMeter(meter);
}
public ParkingTicket getExpired(PoliceOfficer officer){
if (meter.getMinutes() - car.getMinutesParked() < 0){
ticket = new ParkingTicket(officer);
return ticket;
}
else
ticket = new ParkingTicket();
return ticket;
}
public String toString(){
String str = "Officer Details\nOfficer's Name: " + name + "\nOfficer's Badge Number: " + badge + "\n\nCar Information: " + car + "\n\nMeter Information: " + meter;
return str;
}
}

adding a else if function for resulting in passed or failed

I'm learning java language and I saw this code. I was wondering if I can add an if else condition that if the grade is below 80, it will print failed and else passed. Like.
System.out.print("Your Grade is ");
if(avg>80)
{
System.out.print("A");
I searched for other links but I can't find anything. I hope someone can help me. Thanks in advance.
import java.util.*;
public class UserInteraction {
public static void main(String[] args) {
UserChoiceManager userChoiceManager = new UserChoiceManager();
UserChoice choice = UserChoice.UNKNOWN;
do {
choice = userChoiceManager.manage();
} while (choice != UserChoice.EXIT);
System.out.println("Thank you for using the system!");
}
}
enum UserChoice {
UNKNOWN(0),
ENTER_SUBJECT(1),
DISPLAY_DATA(2),
CALCULATE_AVERAGE_GRADE(3),
EXIT(4);
private int id;
public int getId() {
return id;
}
UserChoice(int id) {
this.id = id;
}
public static UserChoice getById(int input) {
for (UserChoice value : UserChoice.values()) {
if (value.getId() == input) {
return value;
}
}
return UserChoice.UNKNOWN;
}
}
class Subject {
private String name;
private int grade;
public Subject(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
class UserChoiceManager {
private final static int SUBJECT_COUNT = 3;
private Subject[] subjects = new Subject[SUBJECT_COUNT];
private Scanner scan = new Scanner(System.in);
public UserChoiceManager() {
}
public UserChoice manage() {
System.out.println(printHelp());
UserChoice choice = getUserChoiceById(scan);
if (choice == UserChoice.ENTER_SUBJECT) {
choice = enterSubjects(choice);
}
if (choice == UserChoice.DISPLAY_DATA) {
printSubjectsAndGrades();
}
if (choice == UserChoice.CALCULATE_AVERAGE_GRADE) {
printAverageGrade();
}
return choice;
}
private static String printHelp() {
StringBuilder usage = new StringBuilder("\nUsage:\n");
usage.append(UserChoice.ENTER_SUBJECT.getId()).append(". Enter a subject name and a corresponding grade").append("\n");
usage.append(UserChoice.DISPLAY_DATA.getId()).append(". Display all grades").append("\n");
usage.append(UserChoice.CALCULATE_AVERAGE_GRADE.getId()).append(". Calculate the average grade").append("\n");
usage.append(UserChoice.EXIT.getId()).append(". Exit system");
return usage.toString();
}
private UserChoice getUserChoiceById(Scanner scan) {
return UserChoice.getById(scan.nextInt());
}
private UserChoice enterSubjects(UserChoice choice) {
System.out.println("Enter " + subjects.length + " subjects and their corresponding grades:");
System.out.println();
for (int i = 0; i < subjects.length; i++) {
String subjectName = scanSubjectName();
int grade = scanGrade();
subjects[i] = new Subject(subjectName.toLowerCase(), grade);
}
System.out.println("Thank you!");
System.out.println();
return choice;
}
private String scanSubjectName() {
Scanner temp = new Scanner(System.in);
String subjectName = "";
do {
System.out.println("Subject:");
subjectName = temp.nextLine();
if (subjectName.equals("")) {
System.out.println("Empty subject name! Try again.");
}
} while (subjectName.equals(""));
return subjectName;
}
private int scanGrade() {
int grade = 0;
do {
Scanner temp = new Scanner(System.in);
System.out.println("Grade:");
try {
grade = temp.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid grade. Enter numeric value! Try again.");
}
} while (grade == 0);
return grade;
}
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
System.out.println("Your average grade is: " + getAverage(subjects));
System.out.println();
}
private void printSubjectsAndGrades() {
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for (int p = 0; p < subjects.length; p++) {
System.out.println(subjects[p].getName() + "\t" + "\t" + subjects[p].getGrade());
}
}
public static double getAverage(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects)
sum += s.getGrade();
return ((double) sum) / subjects.length;
}
public static double getSum(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects) {
sum += s.getGrade();
}
return sum;
}
}
I tried adding some if functions in print out tag but it's not working.
Change your implementation of printAverageGrade to this, and the program will print out what you want:
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
double average = getAverage(subjects);
System.out.println("Your average grade is: " + average);
System.out.print("Your Grade is ");
if (average > 80) {
System.out.println("A");
} else {
System.out.println("Failed");
}
System.out.println();
}

my psvm class doesnt run the other classes and methods

My program is not running. It must be something with calling in the classes from my psvm.
I have inserted my main class and I want the class with the following methods to run. It runs the program, but the class: course with its methods is not activated.
public class main {
public static void main(String[] args) {
Course task1 = new Course();
task1.Assignment1();
}}
The other class
public class Course {
CourseGrades[] course;
public void Assignment1() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to students database");
System.out.println("Enter a to enter a student");
char choice = sc.next().charAt(0);
if (choice > 'z' || choice > 'a') {
System.out.println("Invalid choice");
} else {
switch (choice) {
case 'a':
numbers();
break;
case 'b':
entering();
break;
case 'c':
printCourse();
break;
}
}
}
public void numbers() {
System.out.println("Enter how many courses taken ");
Scanner numbers = new Scanner(System.in);
int courses = numbers.nextInt();
CourseGrades[] course = new CourseGrades[courses];
}
public void entering() {
for (int i = 0; i < course.length; i++) {
System.out.println("Enter coursename");
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
String courseName = sc.nextLine();
course[i] = new CourseGrades();
course[i].setName(courseName);
System.out.println("Enter grade");
Scanner grade = new Scanner(System.in);
course[i].setGrade(i);
}
}
public void printCourse() {
System.out.println("Printing out courses and grades");
for (int i = 0; i < course.length; i++) {
System.out.println(" name 2" + course[i].getName() + " grade" + course[i].getGrade());
}
}
}
Getters and setters
public class CourseGrades {
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
If you have multiple classes in your code then you should always save with the class which having main() method (in this case Main.java), and that class only should be contains public access specifier. I run same code in my IDE. i am run your code successfully in MY IDE:
See the code:
public class Main {
public static void main(String[] args) {
Course task1 = new Course();
task1.Assignment1();
}
}
// The other class
class Course {
CourseGrades[] course;
public void Assignment1() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to students database");
System.out.println("Enter a to enter a student");
char choice = sc.next().charAt(0);
if (choice > 'z' || choice > 'a') {
System.out.println("Invalid choice");
} else {
switch (choice) {
case 'a':
numbers();
break;
case 'b':
entering();
break;
case 'c':
printCourse();
break;
}
}
}
public void numbers() {
System.out.println("Enter how many courses taken ");
Scanner numbers = new Scanner(System.in);
int courses = numbers.nextInt();
CourseGrades[] course = new CourseGrades[courses];
}
public void entering() {
for (int i = 0; i < course.length; i++) {
System.out.println("Enter coursename");
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
String courseName = sc.nextLine();
course[i] = new CourseGrades();
course[i].setName(courseName);
System.out.println("Enter grade");
Scanner grade = new Scanner(System.in);
course[i].setGrade(i);
}
}
public void printCourse() {
System.out.println("Printing out courses and grades");
for (int i = 0; i < course.length; i++) {
System.out.println(" name 2" + course[i].getName() + " grade" + course[i].getGrade());
}
}
}
// Getters and setters
class CourseGrades {
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
Results:
Welcome to students database
Enter a to enter a student
a
Enter how many courses taken
3

Having trouble with searching in an Arraylist

I'm doing a program for school that requires me to do things like add/remove/edit/search bands on the Hall of Fame, with which the user adds bands to. I'm having trouble getting the index of a band in the arraylist hallOfFame. Can anybody recommend any solution to this?
Here is my HallofFame Class:
import java.util.*;
public class HallofFame
{
public static ArrayList<Band> hallOfFame = new ArrayList<Band>();
public static Scanner scan = new Scanner(System.in);
public static void main(String[]args){
boolean running = true;
while(running == true){
System.out.println("What would you like to do?");
System.out.println("");
System.out.println("1. Add");
System.out.println("2. Remove");
System.out.println("3. Edit");
System.out.println("4. Clear");
System.out.println("5. Search");
System.out.println("6. Quit");
System.out.println("");
String choice = scan.nextLine();
if(choice.equals ("1")){
add();
}
else if(choice.equals ("2")){
remove();
}
else if(choice.equals ("3")){
edit();
}
else if(choice.equals ("4")){
clear();
}
else if(choice.equals ("5")){
search();
}
else if(choice.equals ("6")){
running = false;
}
}
}
public static void add(){
Scanner booblean = new Scanner(System.in);
System.out.println("What is the name of the band you would like to add?");
String name = scan.nextLine();
System.out.println("What kind of genre is this band?");
String genre = scan.nextLine();
System.out.println("How many members are in the band?");
int numMem = scan.nextInt();
System.out.println("How many songs does this band have?");
int numSongs = scan.nextInt();
System.out.println("How many albums does this band have?");
int numAlbs = scan.nextInt();
System.out.println("Is this band currently active?");
String yesno = booblean.nextLine();
boolean isActive = false;
if(yesno.equalsIgnoreCase ("yes")){
isActive = true;
}
Band b1 = new Band(name, genre, numMem, numSongs, numAlbs, isActive);
hallOfFame.add(b1);
System.out.println("");
System.out.println("The band " + name + " has been added to the database.");
System.out.println("");
}
public static void remove(){
}
public static void edit(){
System.out.println("What band info do you want to edit?");
String editband = scan.nextLine();
}
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
}
public static void clear(){
hallOfFame.clear();
}
}
And here's the code to the class Band:
public class Band
{
//1.Class Variables
private String nameOfBand;
private String[] members;
private String genre;
private int numberOfMembers;
private int numberOfSongs;
private int numberOfAlbums;
private boolean isActive;
//2. Constructors
public Band(String name, String genre, int numMem, int numSongs, int numAlbs, boolean isActive)
{
}
//3. Methods
//setters
public void setName(String newName)
{
nameOfBand = newName;
}
public void setGenre(String s)
{
genre = s;
}
public void setNumberOfMembers(int num)
{
numberOfMembers = num;
}
public void setNumberOfSongs(int numsongs){
numberOfSongs = numsongs;
}
public void setNumberOfAlbums(int numalbs){
numberOfAlbums = numalbs;
}
public void setIsActive(boolean isactive){
isActive = isactive;
}
public String getName()
{
return nameOfBand;
}
public String getGenre(){
return genre;
}
public int getNumberofMembers(){
return numberOfMembers;
}
public int getNumberofSongs(){
return numberOfSongs;
}
public int getNumberofAlbums(){
return numberOfAlbums;
}
public boolean getIsActive(){
return isActive;
}
#Override public String toString()
{
String output = "";
output += "Name: " + nameOfBand + "\n";
output += "Genre: " + genre + "\n";
output += "Number of members: " + numberOfMembers + "\n";
output += "Number of songs: " + numberOfSongs + "\n";
output += "Number of albums: " + numberOfAlbums + "\n";
output += "Is this band active: " + isActive + "\n";
return output;
}
}
You can do the following code to search Band with name in ArrayList.
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
boolean bandFooud = false;
for(Band band : hallOfFame)
{
if(band.getName().equals(searchband))
{
bandFooud = true;// Set the flag to true to indicate the band is found.
//Make your code to display the band information here.
break;
}
}
if(!bandFooud){
System.out.printf("Band %s is not found.");
}
}
Maybe you want something like this
public static Band search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
for (Band b : hallOfFame){
if (searchBand.equals(b.name){
return b;
break;
}
}
return null;
}
Also, consider override the toString() method in Band if you want the search() method to return void and just print out the Band info.
public class Band
{
//1.Class Variables
private String nameOfBand;
private String[] members;
private String genre;
private int numberOfMembers;
private int numberOfSongs;
private int numberOfAlbums;
private boolean isActive;
//2. Constructors
public Band(String name, String genre, int numMem, int numSongs,
int numAlbs, boolean isActive)
{
nameOfBand = name;
this.genre = genre;
numberOfMemembers = numMem;
numberOfSongs = numSongs;
numberOfAlbums = numAlbs;
this.isActive = isActive;
}
#Override
public String toString(){
return "Name: " + nameOfBand "
+ "Genre: " + genre
+ " Members: " + numOfMembers
+ " Songs: " + numOfSongs
+ " Albums:" + numOfAlbums
+ " Active? " + isActive;
}
Then you could do this
public static void search(){
System.out.println("What band are you looking for?");
String searchband = scan.nextLine();
for (Band b : hallOfFame){
if (searchBand.equals(b.name){
System.out.println(b);
break;
}
}
}

Categories

Resources