So I took everyone's feedback and information and have spent quite a bit of time trying to work on my code prior to submitting. Here are the changes that I have:
import java.util.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class Automobiles {
String make;
String model;
String color;
int year;
int mileage;
int i;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public void setMake(String make) {
this.make = make;
}
public Automobiles() {
make = "";
model = "";
color = "";
year = 0;
mileage = 0;
}
public void Inventory(String make, String model, String color, int year, int mileage) {
System.out.println("Car is: " + make + " " + model + " " + color + " " + year + " " + mileage);
}
String getMake() {
return make;
}
}
public class AutomobileInventory {
public static void main(String[] args)
{
Automobiles[] carInventory = new Automobiles[15];
int i;
String fileName = "out.txt";
boolean quit = false;
String quit1 = "No";
Scanner scnr = new Scanner(System.in);
while (quit1 != "Yes") {
for(i=0; i<carInventory.length; i++) {
carInventory[i] = new Automobiles();
System.out.println("");
System.out.println("Please Enter the make of the vehicle: ");
carInventory[i].make = scnr.nextLine();
System.out.println("Please Enter the model of the vehicle: ");
carInventory[i].model = scnr.nextLine();
System.out.println("Please Enter the vehicle color: ");
carInventory[i].color = scnr.nextLine();
System.out.println("Please Enter the year of the vehicle: ");
carInventory[i].year = scnr.nextInt();
System.out.println("Please Enter the vehicle's mileage: ");
carInventory[i].mileage = scnr.nextInt();
System.out.println("Are you done? Yes or No");
quit1 = scnr.nextLine();
}
}
for(i=0; i<carInventory.length; i++)
System.out.println(carInventory[i].make + " " + carInventory[i].model + " " + carInventory[i].color + " " + carInventory[i].year + " " + carInventory[i].mileage);
try {
PrintWriter outputstream = new PrintWriter(fileName);
outputstream.println(carInventory[i].make + " " + carInventory[i].model + " " + carInventory[i].color + " " + carInventory[i].year + " " + carInventory[i].mileage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running into an issue now that as it completes the loop the first and second instance are combining and it is not allowing me to enter a string for Make each time. Also when I printed to a file it only printed one instance and not all of the instances. Any help is appreciated.
Because you aren't initializing the quit variable, and are using a do-while loop, the loop executes once without checking if quit = "quit". This causes the loop to appear to execute fine, but then crash on the second iteration.
If we examine the structure of how the loop executes:
1) Print "Car Model:"
2) Print "Car Make:"
3) Print "Car Color:"
4) Print "Car Year:"
5) Print "Car Mileage:"
6) Execute For loop
7) Evaluate whether quit == "quit"
8) Print "Car Model"
9) Etc...
When step #7 attempts to evaluate the equality, it is actually performing this comparison:
!null.equalsIgnoreCase("quit"));
Because above in the code, the variable quit was never initialized, and is still set to null. The two code snippets below are in essence equivalent:
// Initialization without assignment:
String quit;
// Explicit initialization to null:
String quitTwo = null;
// Output
print quit
// >> NullPointerException
print quitTwo
// >> NullPointerException
Your Automobile class is fine.
In your automobileInventory class, your are initializing static data member in a non-static method (Check the function where you are initializing the automobiles array).
You can simply initialize it where you are declaring it i.e.:
private static Automobile[] automobiles = new Automobile[ INVENTORY_SIZE ];
Another way is to initialize it in a static block i.e.:
private static Automobile[] automobiles;
static {
automobiles = new Automobile[ INVENTORY_SIZE ];
}
Another way is to initialize it in your function before your loop.
In your sentinel-controlled loop, you are checking exit condition on quit variable but you are not assigning it anything. You need to get value from user whether he/she intends to quit or not.
Here's an example:
String quit; // In your function; not a class member
do {
// ... Rest of your code ...
System.out.println("Do you want to quit [Yes/No]? ");
quit = scnr.nextLine();
}
while ( !quit.equalsIgnoreCase("yes") );
And, you need to take care of your array instance of automobiles that it is correctly being populated. You need to take care of its index that it remains valid.
String quit; // In your function; not a class member
int i = 0;
do {
// ... Rest of your code ...
if ( i < INVENTORY_SIZE ) {
automobiles[i] = new Automobile(make, model, color, year, mileage);
i++;
}
else {
// ... Display error message here that array is full ...
// ... You can then break this loop to exit if you want to ...
break;
}
System.out.println("Do you want to quit [Yes/No]? ");
quit = scnr.nextLine();
}
while ( !quit.equalsIgnoreCase("yes") );
Here's your working code: https://ideone.com/JqX9Y9
Some of the lines are commented for my own testing. You can easily correlate the changes with this answer and figure out yourself what is going on.
Best of luck!
Happy coding!
As #kushagra mentioned, you need to initialize your quit variable. It's currently null, hence the NullPointerException (trying to call a method that doesn't yet exist for your variable)
One tip regarding your quit variable though, I would change it to type boolean since all you need is a true/false. This way, you don't have to do any string comparisons. It would look something like this:
boolean quit = false;
...
do { /* loop stuff */ }
while(quit != true);
Then in your do loop, you can add logic to change your quit variable to true when your user is ready to quit.
Regarding your inventory, I wouldn't use an array if you don't have to; I would use a list (arrays can't change size, whereas lists can). Then instead of using your for loop (you're already looping with your do-while - makes it a little redundant), you can add a new automobile to your list where you currently have it commented out. It would look something like this:
private static List<Automobile> automobiles;
...
automobiles.add(new Automobile(make, model, Color, year, mileage));
UPDATE
Your code is pretty messy - make sure you're consistent with your tabbing/spacing/etc. You should also come up with a clean way of organizing your methods. For example, I like to keep all my getters and setters together with constructors right below the class properties. The bottom of the class is where I like to keep general class methods, overridden methods, etc.
One issue you have with your code is in your main(...); try not to loop within loops if you don't have to (obviously there are always exceptions, such as multidimensional arrays, traversing "grids", etc) - this can slow down execution quite a bit (check out Big O notation - this is a pretty good article: https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/). This will also help you keep track of when your loop closes.
Your file write only happens once because you're not looping (this is where consistent indentation/spacing may help you).
Couple more quick tips: whenever you reuse a value, make a variable for it. You did this a few times, but there were several instances where you could have used a variable (remember: method calls take time to run, so limiting redundant calls will speed up your program). Also, don't be afraid to override the toString() method in your classes - the automobiles class is actually a really good use case for it.
I tried not to give you all the answers, but I've rewritten your code a bit to help you get going:
import java.util.ArrayList;
import java.util.List;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class Automobiles {
String color = "";
String make = "";
String mileage = "";
String model = "";
String year = "";
// -------------------- getters -------------------- //
public String getColor() { return color; }
public String getMake() { return make; }
public String getModel() { return model; }
public String getMileage() { return mileage; }
public String getYear() { return year; }
// -------------------- setters -------------------- //
public void setColor(String color) { this.color = color; }
public void setMake(String make) { this.make = make; }
public void setMileage(String mileage) { this.mileage = mileage; }
public void setModel(String model) { this.model = model; }
public void setYear(String year) { this.year = year; }
#Override
public String toString() {
return year + " " + model + " " + make;
}// end toString()
}// end class Automobiles
public class AutomobileInventory {
public static void main(String[] args) {
List<Automobiles> carInventory = new ArrayList<>();
String fileName = "out.txt";
boolean quit = false;
Scanner scnr = new Scanner(System.in);
do {
Automobiles car = new Automobiles();
System.out.println("Please Enter the year of the vehicle: ");
car.setYear(scnr.nextLine());
System.out.println("Please Enter the make of the vehicle: ");
car.setMake(scnr.nextLine());
System.out.println("Please Enter the model of the vehicle: ");
car.setModel(scnr.nextLine());
System.out.println("Please Enter the vehicle color: ");
car.setColor(scnr.nextLine());
System.out.println("Please Enter the vehicle's mileage: ");
car.setMileage(scnr.nextLine());
carInventory.add(car);
System.out.println("Are you done? Yes or No");
quit = "yes".equals(scnr.nextLine().trim().toLowerCase()) ? true : false;
} while(quit == false);// end do-while-loop
int numCars = carInventory.size();
for(int i = 0; i < numCars; i++) {
String currentCar = carInventory.get(i).toString();
System.out.println(currentCar);
try {
PrintWriter outputstream = new PrintWriter(fileName);
outputstream.println(currentCar);
} catch( FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// end try-catch
}// end for-loop
}// end main(String[] args)
}// end class AutomobileInventory
Related
I'm just practicing java and at the moment I am currently experimenting with getter/setter methods and constructors. The java program works as I am able to store the user inputs into the object but when I input the String "Dice and rollers" into the gametype string variable, a Suspended uncaught exception InputMismatch error comes up.
This is the error I'm getting whenever I input "Dice and Rollers"
However, if I use String variables that does not include spaces, it works fine.
Can someone please explain to me why this is?
Ps. I've shared my source code below.
package test;
import java.util.Scanner;
public class Test8a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the following information: Boardgame name, Alternative Name, Game Type, Year Released, Price and Maximum amount of Players");
String name = in.next();
String secondaryname = in.next();
String type = in.next();
int date = in.nextInt();
double price = in.nextDouble();
int player = in.nextInt();
System.out.println();
new Test8b(name, secondaryname, type, date, price, player);
}
}
The one above is the superclass while the source code below is the constructor and getter/setter java file.
package test;
public class Test8b {
private String boardname;
private String secondaryname;
private String gametype;
private int date;
private double price;
private int numberofPlayers;
public Test8b(String boardname, String secondaryname, String gametype, int date, double price, int players) {
setBoardname(boardname);
setSecondaryname(secondaryname);
setGametype(gametype);
setDate(date);
setPrice(price);
setNumberofPlayers(players);
this.printDetails();
}
public String getBoardname() {
return boardname;
}
public String getSecondaryname() {
return secondaryname;
}
public String getGametype() {
return gametype;
}
public int getDate() {
return date;
}
public double getPrice() {
return price;
}
public int getNumberofPlayers() {
return numberofPlayers;
}
public void setBoardname(String boardname) {
if (boardname.length() >= 15) {
System.out.println("There is no boardgame with this name length! Please enter a valid name!");
} else this.boardname = boardname;
}
public void setSecondaryname (String secondaryname) {
if (secondaryname.length() >= 15) {
System.out.println("There is no boardgame with this name length! Please enter a valid name!");
} else this.secondaryname = secondaryname;
}
public void setGametype(String gametype) {
this.gametype = gametype;
}
public void setDate(int date) {
if (date > 2021) {
System.out.println("This game haven't been invented yet or are you a time traveller?");
} else this.date = date;
}
public void setPrice(double price) {
if (price <= 0) {
System.out.println("Can't give away free games!");
} else this.price = price;
}
public void setNumberofPlayers(int numberofPlayers) {
if (numberofPlayers <= 0) {
System.out.println("Need someone to play the game!");
} else this.numberofPlayers = numberofPlayers;
}
public void printDetails() {
System.out.print(
"Board Game: " + this.getBoardname() + "\n" +
"Alternative Title: " + this.getSecondaryname() + "\n" +
"Game Type: " + this.getGametype() + "\n" +
"Year Released: " + this.getDate() + "\n" +
"Price: " + this.getPrice() + "\n" +
"Maximum # of Players: " + this.getNumberofPlayers() + "\n"
);
}
}
The exception is being thrown by the Scanner object's next() method because the input when you enter a string with spaces does not match the Scanner's default delimiter pattern used for scanning. When you enter a String with spaces, the Scanner sees a line of characters, not just one word of input. In other words, it it differentiates between a single word and a line of words separated by white spaces.
The java.util.Scanner.nextLine() method advances the scanner past the current line and returns the input that was skipped and is the method you should use to scan the game type. Modify your code to use Scanner.nextLine() for the game type and any other type that may have multiple words in it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So everything works great in my program, but I read that making variable not private in class is a big mistake, because it can make problems with others part of big program.
Well I tried making HashMap airplane and flight private but I get error that "The field Airplane.airplane is not visible",which is of course true.
But how do I then make it visible in interface class?
Thanks in advance, I'm still learning and I got to this part in course.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
Airplane airplane = new Airplane();
flight flight = new flight();
interface_aerodrom ui = new interface_aerodrom(imeskanera,airplane,flight);
ui.start();
}
}
/ Airplane class
import java.util.HashMap;
public class Airplane {
HashMap<String,Integer>airplane;
private String id;
private int capacity;
public Airplane() {
this.airplane = new HashMap<String,Integer>();
}
public void add(String id, int capacity) {
this.id = id;
this.capacity = capacity;
this.airplane.put(id, capacity);
}
public String id() {
return this.id;
}
public int capacity() {
return this.capacity;
}
public String airplaneinfo() {
return this.id + "( " + this.capacity + " )";
}
}
/interface class
import java.util.Scanner;
public class interface_aerodrom {
private Scanner imeskanera;
private Airplane airplane;
private flight flight;
public interface_aerodrom(Scanner scanner, Airplane airplane,flight flight) {
this.imeskanera = scanner;
this.airplane = airplane;
this.flight = flight;
}
public void start() {
System.out.println("Airport panel\r\n"
+ "--------------------");
System.out.println();
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Add airplane\r\n"
+ "[2] Add flight\r\n"
+ "[x] Exit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("x")) {
flight_service();
break;
}
else if(input.equals("1")) {
addairplane();
}
else if(input.equals("2")){
addflight();
}
}
}
public void flight_service() {
System.out.println("Flight service\r\n"
+ "------------");
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Print planes\r\n"
+ "[2] Print flights\r\n"
+ "[3] Print plane info\r\n"
+ "[x] Quit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("quit")){
break;
}
else if(input.equals("1")) {
for(String name : this.airplane.airplane.keySet()) {
int numberofseats = this.airplane.airplane.get(name);
String list = name + "( " + numberofseats + " )";
System.out.println(list);
}
}
else if(input.equals("2")){
for(String name : this.flight.flight.keySet()) {
String value = this.flight.flight.get(name);
String list = name + value;
System.out.println(list);
}
}
else if(input.equals("3")) {
System.out.println("Give plane ID: ");
String planeid = this.imeskanera.nextLine();
if(airplanecontains(planeid)) {
int numberofseats = this.airplane.airplane.get(planeid);
System.out.println(planeid + "( " + numberofseats + " )" );
} else {
System.out.println("That plane is not in our database");
}
}
}
}
public void addairplane() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(this.imeskanera.nextLine());
this.airplane.add(ID, capacity);
}
public boolean airplanecontains(String ID) {
if(this.airplane.airplane.containsKey(ID)) {
return true;
}else {
return false;
}
}
public void addflight() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
if(airplanecontains(ID)) {
System.out.println("Give departure airport code: ");
String departure = this.imeskanera.nextLine();
System.out.println("Give destination airport code: ");
String destination = this.imeskanera.nextLine();
int seats = this.airplane.airplane.get(ID);
this.flight.flight.put(ID + " ( " + seats + " ) ",departure + "-" + destination);
}
else {
System.out.println("This plane is not in our database");
}
}
}
/ flight class
import java.util.HashMap;
public class flight {
HashMap<String,String>flight;
public flight() {
this.flight = new HashMap<String,String>();
}
public void add(String departure, String destination) {
this.flight.put(departure, destination);
}
}
Making a field private does not necessarily mean you can't share it. You can use a getter to return the HashMap.
private Map<String,Integer>airplane = new HashMap<>();
public Map<String,Integer> getAirPlaneMap() {
return airplane;
}
The reason being is that this hides implementation details and allows for future changes without affecting users of the class. Users don't need to know where the map comes from within your class. You could have retrieved it from some where yourself and the user wouldn't know.
You may also want to ensure a user can't change it. So you could do the following:
public Map<String,Integer> getAirPlaneMap() {
return Collections.unModifiableMap(airplane);
}
The above will prevent the user from adding or deleting map elements. But it won't prevent them from changing a retrieved object from the map unless that object is also immutable.
In general, setter and getters are the best way to allow users to set and retrieve values. And it is usually a good idea to make defensive copies of mutable items that they are retrieving to ensure that the retrieved values are consistent for all users during execution of the program.
I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi,
I need help in the field of validating data. For some reason i keep getting a incompatible error. I checked a couple times now that I have the right type. What is wrong, 2 classes. The error is int the driver class keep bringing incompatibale tyoes in "name = student.setName( input);". Please explain why?
/*
* Joel Gordon
* per.4
*/
import java.util.Scanner;
public class P5A
{
public static void main (String args[])
{
Scanner reader = new Scanner(System.in);
student student = new student();
String name, validate, valtests;
int tests, score, count = 100;
String input = reader.nextLine();
System.out.println( "Please enter the students Name: " + input);
name = student.setName( input);
validate = student.validateData( name );
System.out.print( "Please enter Test " + count + "(As number 1-3 for test number, then test score): ");
tests = student.getScore( reader.nextInt(), reader.nextInt());
valtests = student.validateTests(tests);
System.out.println( stu.toString());
}//end of main mthod
}//end of main class/Driver
End of student Class driver.
public class student
{
private String name, result;
private int test1, test2, test3;
public student ()
{
name = "";
test1 = 0;
test2 = 0;
test3 = 0;
result = "";
}//constructor
public void setName (String nm)
{
name = nm;
}//setting the name in the program
public String getName ()
{
return name;
}//getting the name
public int getScore (int i, int score)
{
if (i == 1) test1 = score;
else if( i == 2)test2 = score;
else test3 = score;
if ( i == 1 )return test1;
else if ( i == 2 ) return test2;
else return test3;
}//getting score of tests
public int getAverage ()
{
int average;
average = (int) Math.round((test1 + test2 + test3)/ 3.0);
return average;
}//getting a average of all the scores
public int getHighScore()
{
int highscore;
highscore = test1;
if (test2 > highscore) highscore = test2;
if (test3 > highscore)highscore = test3;
return highscore;
}//getting the highscores of all three
public String validateData(String name)
{
if (name.equals("") ) result = "You have entered an invalid name, Please restart." ;
return result;
}
public String validateTests ( int tests )
{
if (test1 >= 0 && test1 <= 100 || test2 >= 0 && test2 <= 100 || test3 >= 0 && test3 <= 100) result = " You have entered an invalid number, between 1-100. " +
"Please restart!" ;
return result;
}//getting the test scores and tesing each one against method
public String toString()
{
String str;
str = "Name: " + name +
"\nTest1: " + test1 +
"\nTest2: " + test2 +
"\nTest3: " + test3 +
"\nAverage: " + getAverage() +
"\nHighscore: " + getHighScore();
return str;
}//putting all the tests together to view in termainal
}
You are struggling with control flow.
What is happening is that when you call your teacher constructor, no matter what, the following lines of code are always executed:
System.out.println ( "I don't have a teacher in that room." );
System.out.println("Always show");
There are a few ways to fix this:
First, you can return; inside your if statements.
Or you can use if then else if then else if then else as the last one for each of your conditions.
Or you can use a switch statement.
You should make Teacher a class representing teacher. Then, you create instances of Teacher objects outside teacher class.
public class Teacher{
private String name;
private String catchPhrase;
private int roomNumber;
public(String name, String catchPhrase, int roomNumber){
this.name = name;
this.catchPhrase = catchPhrase;
this.roomNumber = roomNumber;
}
//put setters and getters here...
public String toString(){
return "Name: "+this.getName()+"\nCatch Phrase: "+this.getCatchPhrase() + "\nRoom Number:
"+this.getRoomNumber();
}
}
Then, you can create Teacher objects. For instance, you can put them in TeacherDriver class.
public class TeacherDriver{
public static void main (String[] args){
//create array of teachers (you can use list and other data structures if you want)
Teacher[] myTeachers = new Teacher[]{
new Teacher("Mr. Clark", "Just do it", 225),
new Teacher("Mr. Harris", "Do the essays and you will pass.", 123)
};
//ask for room number input here...
//mark this truE if teacher is found
boolean found = false;
//search the array of teachers for a match
for(Teacher chosenTeacher : myTeachers)
//if the room number of the teacher matches your target room number
//then display teacher info and stop reading the array
//note: replace <your input room number> with your input variable name
if(chosenTeacher.getRoomNumber() == <your input room number>){
found = true;
System.out.println(chosenTeacher.toString());
break; //stop the loop
}
}
if(!found){
System.out.println ( "I don't have a teacher in that room." );
}
}
A better way to do this though is to create another class that holds collection/array of Teacher objects.
Example:
public class TeacherList{
List<Teacher> teachers;
public TeacherList(){
teachers = new ArrayList<>();
//you can put initial entries like:
teacher.add(new Teacher("Mr. Clark", "Just do it", 225));
teacher.add( new Teacher("Mr. Harris", "Do the essays and you will pass.", 123));
}
public void add(Teacher e){
teachers.add(e);
}
public void findTeacher(int roomNumber){
//mark this tru if teacher is found
boolean found = false;
//search
for(Teacher chosenTeacher : teachers)
//if the room number of the teacher matches your target room number
//then display teacher info and stop reading the array
//note: replace <your input room number> with your input variable name
if(chosenTeacher.getRoomNumber() == <your input room number>){
found = true;
System.out.println(chosenTeacher.toString());
break; //stop the loop
}
}
if(!found){
System.out.println ( "I don't have a teacher in that room." );
}
}
}
Then, in your main:
//create Teacher list
TeacherList myTeachers = new TeacherList();
//input room number here...
//replace <room number? with input variable name
myTeachers.findTeacher(<room number>);
If you want to accept multiple room numbers, then you can put the last two lines of codes above inside a loop.
This is my Code that I have so far:
import java.util.*;
public class VoteRecorder
{
// Variables and instance variables
public static String nameCandidatePresident1;
public static String nameCandidatePresident2;
public static String nameCandidateVicePresident1;
public static String nameCandidateVicePresident2;
public static int votesCandidatePresident1;
public static int votesCandidatePresident2;
public static int votesCandidateVicePresident1;
public static int votesCandidateVicePresident2;
private int myVoteForPresident;
private int myVoteForVicePresident;
public VoteRecorder()
{
nameCandidatePresident1 = "null";
nameCandidatePresident2 = "null";
nameCandidateVicePresident1 = "null";
nameCandidateVicePresident2 = "null";
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
myVoteForPresident = 0;
myVoteForVicePresident = 0;
}
public void setCandidatesPresident(String name1, String name2)
{
nameCandidatePresident1 = name1;
nameCandidatePresident2 = name2;
}
public void setCandidatesVicePresident(String name1, String name2)
{
nameCandidateVicePresident1 = name1;
nameCandidateVicePresident2 = name2;
}
public static void resetVotes()
{
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
}
public static String getCurrentVotePresident()
{
return nameCandidatePresident1 + ":" + votesCandidatePresident1 + "\n" +
nameCandidatePresident2 + ":" + votesCandidatePresident2;
}
public static String getCurrentVoteVicePresident()
{
return nameCandidateVicePresident1 + ":" + votesCandidateVicePresident1 + "\n" +
nameCandidateVicePresident2 + ":" + votesCandidateVicePresident2;
}
public void getAndConfirmVotes()
{
}
private String getVotes()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("please vote for a President or vice president " + nameCandidatePresident1 + ", " + nameCandidatePresident2 + ", " + nameCandidateVicePresident1
+ " or " + nameCandidateVicePresident2);
String presidentVote = keyboard.nextLine();
if (presidentVote.equalsIgnoreCase(nameCandidatePresident1))
return nameCandidatePresident1;
if(presidentVote.equalsIgnoreCase(nameCandidatePresident2))
return nameCandidatePresident1;
System.out.println("please vote for a Vice president " + nameCandidateVicePresident1 + " or" + nameCandidateVicePresident2);
String vicePresidentVote = keyboard.nextLine();
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident1))
return nameCandidateVicePresident1;
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident2))
return nameCandidateVicePresident2;
else
return "not a valid vote";
}
private boolean confirmVotes()
{
System.out.println("Your vote for President is:");
System.out.println("your vote for Vice President is:");
System.out.println("Is this correct? Yes or No?");
Scanner keyboard = new Scanner(System.in);
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes"))
return true;
else
return false;
}
private void recordVote()
{
puscode: If confirmVotes returns true, take the nameCandidate, and ++ to votesCandidate of the same type
Copy this If statement four times, one for each of the candidates, 2 president and 2 vp.
Else or If confirmvotes returns false, put output saying that the votes were not confirmed.
}
}
Say i had all this code, lets look at the method getVotes() and confrimVotes(), in getVotes() the user picks a candidate and than that candidate is returned. How would i get that return statement to show up else where in other methods? like in confirmVote() i want to do this
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
But how can i do that?
This is not a direct answer to your question, but I think your code could be made a lot simpler by harnessing some of the power of object-oriented programming.
You are storing multiple types of information about 4 candidates for different positions as separate variables, and it's making your class very unwieldy.
A (in my opinion) better approach would be to have e.g. a Candidate class to store information about a single candidate, and then your classes could look as follows:
class Candidate {
String Name;
int votes;
}
class VoteRecorder {
Candidate[] presidents;
Candidate[] vicePresidents;
Candidate myVoteForPresident; //Or even make these both ints.
Candidate myVoteForVicePresident;
}
The classes can be further refined, but this will be a start. Any time you see multiple pieces of information that describe the same entity being repeated multiple times, it's a good indication that you could simplify your life by adding a class to represent them together instead.
Edit (to answer question specifically):
If you want to do effectively the following:
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
You can write something like this:
String voteResult = getVotes();
System.out.println("Your vote for President is: " + voteResult);
Or in one line:
System.out.println("Your vote for President is: " + getVotes());
Each time you run this code though, it will prompt the user for input. If you want to save the result until next time as well, you will have to save it to an attribute, e.g. by having a string in your class, and assigning the value to it first. Then just use that later instead of the local variable voteResult.