I've got a class, "vehicle" which should allow the array to be saved with the information input by the user but when I try and get the method to accept the data with the counter giving each data entry a unique number it doesn't accept anything past the [ on vehicle vehiclearray[totalcount] = new vehiclearray(count,licence,date,value,colour); I'm relatively new to java and this problem has stumped me, any help would be appreciated.
This is the whole code, the problem is under submenu1.
import java.util.Scanner;
class main
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int option = menu();
int totalcount = submenu1.totalcount;
int carcount = submenu1.carcount;
int bikecount = submenu1.bikecount;
vehicle vehiclearray[] = new vehiclearray[100];
if (option == 1)
submenu1(vehiclearray);
else if (option ==2)
submenu2(totalcount, vehiclearray);
else if (option ==3)
submenu3(totalcount, carcount, bikecount,museumbike, museumcar);
else if (option ==4)
submenu4(carcount, museumcar);
else if (option ==5)
submenu5(bikecount, museumbike);
else if (option ==6)
System.out.println("Thank you for using this program");
else
System.out.println("Invalid selection, please try again.");
}
}
class menusystem
{
public static int menu()
{
Scanner input = new Scanner (System.in);
int option = 0;
System.out.println("Please select an option");
System.out.println("=======================");
System.out.println("1. Add a vehicle to the collection");
System.out.println("2. List vehices manufactured by a specifit year");
System.out.println("3. List all vehcles of a certain engine size or more");
System.out.println("4. list all cars");
System.out.println("5. List all bikes");
System.out.println("6. Exit");
option = input.nextInt();
return option;
}
public static int submenu1(vehicle vehiclearray[])
{
Scanner input = new Scanner (System.in);
String suboption1;
int totalcount = carcount = bikecount = 1;
System.out.println("Is the vehicle a car or a bike? (exit to close)");
suboption1 = input.next();
while(!suboption1.equalsIgnoreCase("exit"))
{
if (suboption1.equalsIgnoreCase("car"))
{
vehicle.id=count;
System.out.println("Please enter the licence, manufacture year, car value and colour of the car");
vehicle vehiclearray[totalcount] = new vehiclearray(count,licence,date,value,colour);
System.out.println("Please enter the number of doors, number of seats, engine type (petrol or deisol) and engine size in litres");
museumcar museumcar[carcount] = new museumcar(cardoors,seats,enginetype,carenginesize);
totalcount++;
carcount++;
}
else if (suboption1.equalsIgnoreCase("bike"))
{
System.out.println("Please enter the licence, manufacture year, car value and colour of the bike");
vehicle vehiclearray[totalcount] = new vehiclearray(licence,date,value,colour);
vehicle.id=count;
System.out.println("Please enter the bike type (sports, tourer or trials) and engine size in cc");
museumbike museumbike[bikecount] = new museumbike(type,bikeenginesize);
totalcount++;
bikecount++;
}
else
System.out.println("Please enter a valid entry.");
System.out.println("Is the vehicle a car or a bike? (exit to close)");
suboption1 = input.next();
return bikecount;
return carcount;
return totalcount;
}
}
public static void submenu2(int totalcount, vehicle vehiclearray[])
{
Scanner input = new Scanner (System.in);
int desiredyear = 0;
int count = 1;
System.out.println("What vehicle manufacture date do you want to see?");
desiredyear = input.nextInt();
for (count = 1; count <= totalcount; count++)
{
if (vehiclearray[totalcount].getdate == desiredyear)
System.out.println(vehiclearray[totalcount] +" id : "+ vehiclearray[totalcount].getlicence(), +" licence : "+ vehiclearray[totalcount].getdate(), +" date : "+ vehiclearray[totalcount].getvalue(), +" value : "+ vehiclearray[totalcount].getcolour() +" colour:");
else
System.out.println(vehiclearray[totalcount] +" does not match the desired manufacture year");
}
}
public static void submenu3(int totalcount, int carcount, int bikecount, museumbike museumbike[], museumcar museumcar[])
{
Scanner input = new Scanner (System.in);
double desiredsize = 0;
int count = 1;
System.out.println("What vehicle size or more do you want to see?");
desiredsize = input.nextDouble();
for (count = 1; count <= totalcount; count++)
{
if (desiredsize >=0 && desiredsize <=100)
{
if (museumcar[carcount].getcarenginesize >= desiredsize)
System.out.println(museumcar[carcount].getcardoors(), +(" doors : ")+ museumcar[carcount].getseats(), +(" seats : ")+ museumcar[carcount].getenginetype(), +(" : ")+ museumcar[carcount].getcarenginesize() +("ltrs"));
else
System.out.println("This car has a lower engine size then the desiredsize");
}
else if (desiredsize >=100)
System.out.println(museumbike[bikecount].gettype(), +(" : ")+ museumbike[bikecount].getbikeenginesize() +("cc"));
}
}
public static void submenu4(int carcount, museumcar museumcar[])
{
int count = 1;
for (count = 1; count <= museumcar[carcount]; count++)
{
System.out.println(museumcar[carcount].getcardoors(), +(" doors : ")+ museumcar[carcount].getseats(), +(" seats : ")+ museumcar[carcount].getenginetype(), +(" : ")+ museumcar[carcount].getcarenginesize() +("ltrs"));
}
}
public static void submenu5(int bikecount, museumbike museumbike[])
{
int count = 1;
for (count = 1; count <= museumbike[bikecount]; count++)
{
System.out.println(("bike id:")+ museumbike[bikecount].gettype(), +(" : ")+ museumbike[bikecount].getbikeenginesize() +("cc"));
}
}
}
class vehicle
{
private int carid;
private String licence;
private int date;
private Double value;
private String colour;
vehicle (int i,String l, int d, double v, String c)
{
id = i;
licence = l;
date = d;
value = v;
colour = c;
}
int getid()
{
return id;
}
String getlicence()
{
return licence;
}
int getdate()
{
return date;
}
Double getvalue()
{
return value;
}
String getcolour()
{
return colour;
}
}
class museumcar extends vehicle
{
private int cardoors;
private int seats;
private String enginetype;
private Double carenginesize;
museumcar (int cd, int s, String et, Double ces)
{
super (i, l, d, v, c);
cardoors = cd;
seats = s;
enginetype = et;
carenginesize = es;
}
int getcardoors()
{
return cardoors;
}
int getseats()
{
return seats;
}
String getenginetype()
{
return enginetype;
}
Double getcarenginesize()
{
return carenginesize;
}
}
class museumbike extends vehicle
{
private String type;
private Double bikeenginesize;
museumbike (String t, Double bes)
{
super (i, l, d, v, c);
type = t;
bikeenginesize = bes;
}
String gettype()
{
return type;
}
Double getbikeenginesize()
{
return bikeenginesize;
}
}
There is no vehiclearray class and so you can't do new vehiclearray[...], but instead should do new vehicle[...].
So for example, this line of code is not legal:
vehicle vehiclearray[] = new vehiclearray[100];
but this is:
vehicle vehiclearray[] = new vehicle[100];
In general I think that most of declare our variable with the array brackets on the class and not on the variable:
vehicle[] vehiclearray = new vehicle[100];
Although your way is legal (if you created the correct array object declaration that is).
Additional Notes:
Your class names should start with a capital letter so as to comply with Java naming conventions so that others (us!) can better understand your code.
If you have a question and your code doesn't compile, you should post any and all full compiler error messages with your question and also indicate which line(s) in your code cause the errors.
Related
Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.
Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}
You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.
So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}
I was writing my program when I came across the following errors at certain spots in my code:
The first error was: "The constructor Gerbil(String, String, int[], boolean, boolean, String[]) is undefined" at the following code: gerbil[i] = new Gerbil(n5,n6,amountfood, escape[i], bite[i],food);
The second error was: "The method getTypeFood() is undefined for the type Gerbil" at the following code: String[]food = g.getTypeFood();
Here is my entire code for the program (2 different classes)
1st class:
import java.util.Scanner;
public class Gerbilfood {
static int n8;
static int n3;
static String n55;
static String n35;
static String n2;
public static Gerbil[] gerbil;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of this food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
//gerbil = new Gerbil[n4];
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
//Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for one of the gerbils");
String n5 = scanner.nextLine();
//g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name given to gerbil whose lab id you just entered");
String n6 = scanner.nextLine(); // gerbil name
//g.setName(n6);
//String[] amountfood = new String[n1];
int [] amountfood = new int[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of " +food[j]
+ " did this gerbil eat");
String n8 = scanner.nextLine();
//amountfood[j = n8;
amountfood[j] = Integer.parseInt(n8);
}
boolean[] bite = new boolean[n4];
System.out
.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
if (n77.equalsIgnoreCase("True"))
bite[i] = true;
else{
bite[i] = false;
}
boolean[]escape = new boolean[n4];
System.out
.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
if (n89.equalsIgnoreCase("True"))
escape[i] = true;
else{
escape[i] = false;
}
gerbil[i] = new Gerbil(n5,n6,amountfood, escape[i], bite[i],food);
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if(n55.equalsIgnoreCase(n34)){
System.out.println( averagefood());
}
else{
if(n55.equalsIgnoreCase(n33)){
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
Gerbil g = searchForGerbil(n87);
Gerbil gerbilattributes=searchForGerbil(n87);
String gerbid = g.getId();
String gerbname = g.getName();
boolean gerbbite = g.getBite();
boolean gerbescape = g.getEscape();
for (int i = 0; i<n1; i++)
String[]food = g.getTypeFood();
int[] gerbfoods = g.getAmountFood();
for(int i = 0; i < n1; i++)
System.out.println(gerbid +" bite = "+ gerbbite + " " + gerbname + "escape = " + gerbescape + " " + gerbfoods);
}
else{
if (n55.equalsIgnoreCase(n35)){
//GO BACK
}
else{
if (n55.equalsIgnoreCase(n36)){
System.exit(0);
}
else{
System.out.println("ERROR");
}
}
}
}
}
public static String averagefood() {
int i = 0;
Gerbil g = gerbil[i];
String gid = g.getId();
String gname = g.getName();
long percent = Math.round(n8 * 100.0 / n3);
String everything = gid + " " + gname + " " + percent + "\n";
for ( i = 0; i <=gerbil.length; i++) {
//turn everything;
}
return everything;
}
public static Gerbil searchForGerbil(String n87) {
for(int i = 0; i< gerbil.length; i++){
Gerbil g = gerbil[i];
if(n87.equals(g.getId())){
return gerbil[i];
}
// return (new Gerbil[i]);
} return null;
}
}
second class:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
private int numbergerbils;
private String[] food;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int[]numOfFood, boolean newEscape, boolean newBite, String[] n2) {
id = n5;
name = n6;
amountfood = numOfFood;
escape = newEscape;
bite = newBite;
food = n2;
}
public Gerbil(String[] typefood){
food = typefood;
}
public Gerbil(int [] numOfFood) {
amountfood = numOfFood;
}
public int[] getAmountFood(){
return amountfood;
}
public boolean getBite(){
return bite;
}
public boolean getEscape(){
return escape;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
public String [] getTypeFood(){
return food;
return null;
}
}
Please input how many types of food items the gerbils eat as an integer
2
Please enter a food name
bread
Please enter maximum amount of this food per day
5
Please enter a food name
garlic
Please enter maximum amount of this food per day
6
Please enter in the number of gerbils in the lab
2
Please enter in the lab id for one of the gerbils
hgklll
Please enter in the name given to gerbil whose lab id you just entered
larry
how much of bread did this gerbil eat
1
how much of garlic did this gerbil eat
1
Does this Gerbil bite? Enter True or False
False
Does this Gerbil escape? Enter True or False
True
Please enter in the lab id for one of the gerbils
hjdddd
Please enter in the name given to gerbil whose lab id you just entered
dave
how much of bread did this gerbil eat
1
how much of garlic did this gerbil eat
1
Does this Gerbil bite? Enter True or False
False
Does this Gerbil escape? Enter True or False
True
What information would you like to know?
search
Please type the lab id of the gerbil you wish to search for
hjdddd
hjdddd bite = false daveescape = true [I#629e5e21
hjdddd bite = false daveescape = true [I#629e5e21
For the last part (Please type in the lab id you wish to search for), I am trying to get it to return the food names and amounts in the string. Example: Name: Big Bertha (will escape, will not bite), Food: Red Pill – 25/50, Blue Pill –
50/100
At a glance below method is wrong hence Gerbil class will not compile.
public String [] getTypeFood(){
return food;
return null;
}
Remove one of the return statement.
public String [] getTypeFood(){
return food;
}
Full code:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
private int numbergerbils;
private String[] food;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int[] numOfFood, boolean newEscape, boolean newBite, String[] n2) {
id = n5;
name = n6;
amountfood = numOfFood;
escape = newEscape;
bite = newBite;
food = n2;
}
public Gerbil(String[] typefood) {
food = typefood;
}
public Gerbil(int[] numOfFood) {
amountfood = numOfFood;
}
public int[] getAmountFood() {
return amountfood;
}
public boolean getBite() {
return bite;
}
public boolean getEscape() {
return escape;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
public String[] getTypeFood() {
return food;
}
}
import java.util.Scanner;
public class Gerbilfood {
static int n8;
static int n3;
static String n55;
static String n35;
static String n2;
public static Gerbil[] gerbil;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of this food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
//gerbil = new Gerbil[n4];
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
//Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for one of the gerbils");
String n5 = scanner.nextLine();
//g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name given to gerbil whose lab id you just entered");
String n6 = scanner.nextLine(); // gerbil name
//g.setName(n6);
//String[] amountfood = new String[n1];
int[] amountfood = new int[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of " + food[j]
+ " did this gerbil eat");
String n8 = scanner.nextLine();
//amountfood[j = n8;
amountfood[j] = Integer.parseInt(n8);
}
boolean[] bite = new boolean[n4];
System.out
.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
if (n77.equalsIgnoreCase("True")) {
bite[i] = true;
} else {
bite[i] = false;
}
boolean[] escape = new boolean[n4];
System.out
.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
if (n89.equalsIgnoreCase("True")) {
escape[i] = true;
} else {
escape[i] = false;
}
gerbil[i] = new Gerbil(n5, n6, amountfood, escape[i], bite[i], food);
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if (n55.equalsIgnoreCase(n34)) {
System.out.println(averagefood());
} else {
if (n55.equalsIgnoreCase(n33)) {
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
Gerbil g = searchForGerbil(n87);
Gerbil gerbilattributes = searchForGerbil(n87);
String gerbid = g.getId();
String gerbname = g.getName();
boolean gerbbite = g.getBite();
boolean gerbescape = g.getEscape();
for (int i = 0; i < n1; i++) {
food = g.getTypeFood();
}
int[] gerbfoods = g.getAmountFood();
System.out.print("Lab :"+gerbid + " Name:"+ gerbname + " ("+ ((gerbbite==true)?"will bite":"will not bite") + "," + ((gerbescape==true)?"will escape":"will not escape") + ")");
for (int i = 0; i < n1; i++) {
System.out.print( " " + food[i] + ":"+ gerbfoods[i]);
}
} else {
if (n55.equalsIgnoreCase(n35)) {
//GO BACK
} else {
if (n55.equalsIgnoreCase(n36)) {
System.exit(0);
} else {
System.out.println("ERROR");
}
}
}
}
}
public static String averagefood() {
int i = 0;
Gerbil g = gerbil[i];
String gid = g.getId();
String gname = g.getName();
long percent = Math.round(n8 * 100.0 / n3);
String everything = gid + " " + gname + " " + percent + "\n";
for (i = 0; i <= gerbil.length; i++) {
//turn everything;
}
return everything;
}
public static Gerbil searchForGerbil(String n87) {
for (int i = 0; i < gerbil.length; i++) {
Gerbil g = gerbil[i];
if (n87.equals(g.getId())) {
return gerbil[i];
}
// return (new Gerbil[i]);
}
return null;
}
}
Assuming you have your two classes in two separate, appropriately named files, here are the two problems:
In Gerbilfood, in your main method you are attempting to redefine the variable food:
String[] food = new String[n1];
...
String[]food = g.getTypeFood();
In Gerbil, your getTypeFood method has two returns:
public String [] getTypeFood(){
return food;
return null;
}
Start by fixing these two problems.
I need to call the method getAmount() from the Service class only. I do not want to add the values of the Purchaser class. Is there a way I can call the method explicitly from the Service class? I have put a ** where I am referring to.
package prog24178.assignment;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 99999; // Max array size.
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt = 0;
double total = 0;
//loop to choose customer type and create a new object.
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press any number besides 1 or 2");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
//loop to print the entries
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
//loop to print the total for the service objects.**THIS IS LOOP I AM //REFFERING TO
for(int i=0; i < cnt; i++ ){
if(cust[i]!= null)
total = cust[i].getAmounts() + total;
}
System.out.println("Monthly invoice total: " + total);
s.close();
}
}
interface Functions {
public void getData();
public void showData();
public double getAmounts();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
//**I DO NOT WANT TO CALL THIS METHOD
public double getAmounts(){
return this.payment;
}
}
class Service extends Customer {
protected String date;
public double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
//**THIS IS THE METHOD I NEED TO CALL
public double getAmounts(){
return this.amount;
}
}
Check your customer for type:
if (cust[i] instanceof Service) {
total = cust[i].getAmounts() + total;
}
That takes care of the null check automatically as well.