This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 years ago.
New here, so please go easy on me! I've searched other articles on the subject but can't quite find the answer i'm looking for. Hoping someone can help.
Two separate classes, object class and main method. I need to print the object details using toString, but I can't work out how to print the toppings, which are being passed as an array from the main method. The code runs ok, but when I call getToppings() from the toString method, it just prints the id of the array object name, rather than the contents of the array itself.
Can anyone help?
Thanks in advance,
Marc
package toString;
/*
* class to represent a pizza object.
*/
public class Pizza
{
private String name;
private String [] toppings;
private double price;
public Pizza(String reqName, String [] reqToppings, double reqPrice)
{
name = reqName;
toppings = reqToppings;
price = reqPrice;
}
public String getName()
{
return name;
}
public String[] getToppings()
{
return toppings;
}
public double getPrice()
{
return price;
}
public String toString()
{
return "The pizza name is " + getName() + ", the toppings are " + getToppings() + " and the price is £" + getPrice();
}
}
package toString;
public class TestPizza
{
public static void main(String[] args)
{
String[] pepperoni = {"Pepperoni", "minced beef"};
String[] diavalo = {"Pepperoni", "minced beef", "chillies"};
String[] chicken = {"Chicken", "sweetcorn"};
Pizza [] pizzaList = new Pizza[3];
pizzaList[0] = new Pizza("Pepperoni", pepperoni, 6.95);
pizzaList[1] = new Pizza("Diavalo", diavalo, 7.95);
pizzaList[2] = new Pizza("Chicken & Sweetcorn", chicken, 8.95);
System.out.println(pizzaList[0].toString());
System.out.println(pizzaList[1].toString());
System.out.println(pizzaList[2].toString());
}
}
You have to go through array and print out every item:
public String toString(){
String s = "The pizza name is " + getName() + ", the toppings are: ";
for(int i = 0; i<getToppings().size; i++){
s += getToppings[i] + ", ";
}
s += "and the price is £" + getPrice();
return s;
}
Related
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'm writing a program that includes a driver sundae program and a sundae class. I get no errors on compilation.
import java.util.Scanner;
public class SundaeDriver
{
public static void main(String[] args)
{
Sundae newSundae = new Sundae();
Scanner input = new Scanner(System.in);
System.out.println("Which sundae flavor would you like? ");
newSundae.setFlavor(input.nextLine());
if ((newSundae.getFlavor().equalsIgnoreCase("vanilla"))||
(newSundae.getFlavor().equalsIgnoreCase("peanut butter"))||
(newSundae.getFlavor().equalsIgnoreCase("chocolate"))||
(newSundae.getFlavor().equalsIgnoreCase("cocoanut"))||
(newSundae.getFlavor().equalsIgnoreCase("cookie dough"))||
(newSundae.getFlavor().equalsIgnoreCase("coffee"))||
(newSundae.getFlavor().equalsIgnoreCase("strawberry"))||
(newSundae.getFlavor().equalsIgnoreCase("butter pecan")))
{
}
else
{
newSundae.setDefault();
newSundae.Print();
}
System.out.println("How many scoops?");
newSundae.setNumberOfScoops(input.nextInt());
if ((newSundae.getNumberOfScoops()==1)||
(newSundae.getNumberOfScoops()==2)||
(newSundae.getNumberOfScoops()==3)||
(newSundae.getNumberOfScoops()==4)||
(newSundae.getNumberOfScoops()==5)||
(newSundae.getNumberOfScoops()==6))
{
}
else
{
newSundae.setDefault();
newSundae.Print();
}
System.out.println("How many free toppings would you like");
int num = input.nextInt();
input.nextLine();
for (int i = 0; i<num;i++)
{
System.out.println("what free toppings would you like?");
String temp=input.nextLine();
if ((temp.equalsIgnoreCase("whipped cream"))||
(temp.equalsIgnoreCase("hot fudge syrup"))||
(temp.equalsIgnoreCase("multi colored sprinkles"))||
(temp.equalsIgnoreCase("cherry")))
{
newSundae.setStdTopping(temp);
}
else
{
newSundae.setDefault();
newSundae.Print();
}
}
System.out.println("What free syrup would you like?");
newSundae.setFreeSyrupChoice(input.nextLine());
if ((newSundae.getFreeSyrupChoice().equalsIgnoreCase("hot fudge"))||
(newSundae.getFreeSyrupChoice().equalsIgnoreCase("chocolate"))||
(newSundae.getFreeSyrupChoice().equalsIgnoreCase("caramel"))||
(newSundae.getFreeSyrupChoice().equalsIgnoreCase("strawberry")))
{
}
else
{
newSundae.setDefault();
newSundae.Print();
}
System.out.println("How many deluxe toppings would you like?");
num = input.nextInt();
input.nextLine();
for (int i = 0; i<num; i++)
{
System.out.println("what extra toppings would you like");
String deluxe=input.nextLine();
if ((deluxe.equalsIgnoreCase("M&Ms"))||
(deluxe.equalsIgnoreCase("crushed oreos"))||
(deluxe.equalsIgnoreCase("reeses peices"))||
(deluxe.equalsIgnoreCase("bwonie crunches"))||
(deluxe.equalsIgnoreCase("mint chocolate chip"))||
(deluxe.equalsIgnoreCase("marshmallows"))||
(deluxe.equalsIgnoreCase("peanuts"))||
(deluxe.equalsIgnoreCase("walnuts"))||
(deluxe.equalsIgnoreCase("peanuts and walnuts")))
{
newSundae.setDeluxTopping(deluxe);
}
else
{
newSundae.setDefault();
newSundae.Print();
}
}
}
}
When the user inputs the correct Sundae flavor, type and number of free toppings and regular toppings, the program is supposed to display the total price at the end. However, The program just ends when the user puts in all the data.
public class Sundae
{
private String flavor;
private int numberOfScoops;
private double costForScoops;
private String [] stdToppingList=new String [4];
private String freeSyrupChoice;
private String [] deluxeToppingList= new String [9];
private int counterD= 0;
private double costOfDeluxeToppings;
private double costOfSundae;
private final double SALES_TAX= .08625;
private double tax;
private final double COST_PER_DELUXE_TOPPING =.75;
private int counterFree=0;
public Sundae()
{
flavor= " vanilla ";
numberOfScoops=2;
costForScoops=2.79;
stdToppingList[0]=" whipped cream ";
stdToppingList[1]=" hot fudge syrup ";
stdToppingList[2]=" multi colored sprinkles ";
stdToppingList[3]=" cherry ";
}
public String getFlavor()
{
return flavor;
}
public int getNumberOfScoops()
{
return numberOfScoops;
}
public double getCostForScoops()
{
return costForScoops;
}
public String [] getStdTopping()
{
return stdToppingList;
}
public String getFreeSyrupChoice()
{
return freeSyrupChoice;
}
public String [] getDeluxeTopping()
{
return deluxeToppingList;
}
public int getCounterD()
{
return counterD;
}
public double getCostDeluxeToppings()
{
return costOfDeluxeToppings;
}
public double getCostOFSundae()
{
return costOfSundae;
}
public void setFlavor( String selection )
{
flavor=selection;
}
public void setNumberOfScoops(int number)
{
numberOfScoops= number;
}
public void setCostForScoops()
{
costForScoops= numberOfScoops + .79;
}
public void setStdTopping( String toppings )
{
stdToppingList[counterFree] = toppings;
counterFree++;
}
public void setFreeSyrupChoice( String syrup )
{
freeSyrupChoice= syrup;
}
public void setDeluxTopping (String xtraToppings)
{
deluxeToppingList[counterD] = xtraToppings;
counterD++;
}
public void setDefault()
{
flavor= " vanilla ";
numberOfScoops= 2;
costForScoops=2.79;
stdToppingList[0] = " whipped cream ";
stdToppingList[1] = " hot fudge syrup ";
stdToppingList[2] = " multi colored sprinkles ";
stdToppingList[3] = " cherry" ;
}
public void Print()
{
System.out.println(flavor + " "+ numberOfScoops+ " " + costForScoops +
" " + stdToppingList[0] + " " + stdToppingList[1] + stdToppingList[2] + stdToppingList[3]);
setCostForScoops();
costOfDeluxeToppings = COST_PER_DELUXE_TOPPING*counterD;
costOfSundae = costOfDeluxeToppings + costForScoops;
tax=SALES_TAX*costOfSundae;
System.out.printf("Subtotal : $%.2f, tax: $%.2f, grand total: $%.2f " ,
costOfSundae, tax, (costOfSundae+tax));
}
}
Whenever the user types in a string or value that is not user defined, I get a weird display message of
C:\Users\DrewS>java SundaeDriver
Which sundae flavor would you like?
yes//purposly inputting value, should default to defsualt flavor vanilla at 2 scoops with all 4 free toppings.
vanilla 2 2.79 [Ljava.lang.String;#5c647e05
Subtotal : $2.79, tax: $0.24, grand total: $3.03 How many scoops?
6
How many free toppings would you like
3
what free toppings would you like?
whipped cream
what free toppings would you like?
hot fudge
vanilla 2 2.79 [Ljava.lang.String;#5c647e05//weird thing keeps printing
Subtotal : $2.79, tax: $0.24, grand total: $3.03 what free toppings would you l
ke?
hot fudge syrup
What free syrup would you like?
chocolate
How many deluxe toppings would you like?
1
what extra toppings would you like?
mint chocolate chip
Your "problem" (its not really a problem, i'll explain) is from :
public void Print()
{
System.out.println(flavor + " "+ numberOfScoops+ " " + costForScoops +
" " +stdToppingList);
You see, when you call println(), java will try to call for each element its method toString()
numberofScoops.toString() works fine, since it's an integer, the method toString() is already defined.
The point is, when the method toString() is not defined for an object, it prints the name of the object and the adress of said object instead, for example if we take your stdToppingList (note that it's a String Table, not a string) :
[Ljava.lang.String;#5c647e05
Ljava.lang.String is what it contains, your object is a String Table. And #5c647e05 is its hashcode.
For "fixing that" , you need to display all elements of your table one by one :
public void Print()
{
System.out.println(flavor + " "+ numberOfScoops+ " " + costForScoops +
" " + stdToppingList[0] + " " + stdToppingList[1] + stdToppingList[2] + stdToppingList[3]);
Since you always have 4 element in your stdToppingList, you can safely print them all. Or you could iterate through it if you were to save the number of toppings the user wants.
OK, now that we've fixed your print() function, let's dig in (Like i usually dig in my sundaes) the main issue, your main. Your main is unholy, going through your main is like seeing the Devil. As i'm writing thoses lines, i pray towards Linus for the Holy Salvation of my soul.
Anyway, let's start by what's wrong in your code :
You set your whole object to Default anytime there's a mistake from the user.
Your if-statements are poorly written. Why aren't you just giving the user the choice of what to choose instead of letting him in the blue ?
When you ask for the number Free Topping, you doesnt check how many the user ask for.I mean, i would love asking for a 99 free toppings, and according to your program i can ... But wait ! You said your number of free Toppings is 4 max. So yeah, it's a flaw
All thoses 3 points above makes your code hard to read, hard to debug, and hard for the user to use;
I'd suggest you refactor your main and come back here once you've done, i'll be waiting for you.
God that made me hungry.
In your print() function you have
System.out.println(flavor + " "+ numberOfScoops+ " " + costForScoops +
" " +stdToppingList);
Where stdToppingList is a String[], not a String. Printing an array will give you that weird thing which javadocs of Object.toString() says is the
the name of the class + `#` + a hexadecimal representation of the object's hashcode
In order to print a primitive array in Java you either get a for loop and print each element and a space between or use something similar to Arrays.toString(stdToppingList).
I apologize for the lengthy submission but I am having some difficulty with getting this program to work correctly.
There is another Driver program that runs this one and it requires me to print out the name, level, supplies, etc., of a Magician (given certain parameters).
However, when I use the toString() method to print out the String. I continuously get a
"null" response for my name/level/supplies. My numbers also seem to not update.
Could someone take a look and see what I am doing wrong?
I just can't seem to make the program pick up the Magician parameters.
public class Magician
{
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String initialValues)
{
double health = 1000;
int galleons = 200;
initialValues = name + "#" + level + "#" + supplies;
}
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
}
This is the beginning of the Driver program that I can not get to print out:
public class MagicAndMalice
{
public static void main (String[] args)
{
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
System.out.println(harry); // test toString() method
System.out.println("------------------------\n\n");
}
}
First, you are declaring health and galleons again. You should not declare them again, just assign the values:
health = 1000;
galleons = 200;
Also, it seems like you are confused about assignment. If you want to assign some value to name, level and supplies, you have to do:
name = ...;
level = ...;
supplies = ...;
If initialValues will contain a string like "a#b#c" and you want to assign each "part" to those variables, you can use String#split():
String[] parts = initialValues.split("#");
name = parts[0];
level = parts[1];
supplies = parts[2];
But I would really recommend you to read a book or follow some tutorials of Java, so you get the basics first.
You are missunderstanding the value assignment thing in Java. You won't need a separator like #, but if you do, you would need to e.g. substr the given String in the constructor.
Here's a short (untested) version, that should clarify what I mean:
public class Magician {
private String name, level, supplies;
private int galleons;
private double health;
public Magician(String name, String level, String supplies) {
health = 1000;
galleons = 200;
this.name = name;
this.level = level;
this.supplies = supplies;
}
// Let's do some Constructor overloading here
public Magician(String initialValueString) {
String[] initialValues = initialValueString.split("#");
this(initialValues[0], initialValues[1], initialValues[2]);
}
public String toString() {
return "Name: " + name +
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " + supplies;
}
}
public class MagicAndMalice {
public static void main (String[] args) {
// Method one
Magician harry = new Magician("Harry Potter", "apprentice", "Wand");
System.out.println(harry);
System.out.println("------------------------\n\n");
// Method two
Magician ron = new Magician("Ron Weasley#apprentice#Owl");
System.out.println(ron);
System.out.println("------------------------\n\n");
}
}
And if you want to have more values than just one in the supplies field, have a look at Array or try to split/substr the values with some regular expressions.
Hope that helped to get some clearer about the variable assignment in Java.
When you create object as
Magician harry = new Magician("Harry Potter#apprentice#Owl#Wand");
only double health = 1000; & int galleons = 200; get initialled as some value.
When you call toString() method then
public String toString()
{
return "Name: " + name+
"Level: " + level +
"Galleons: " + galleons +
"Health: " + health +
"Supplies: " +supplies;
}
the value null for some field is returned because it is not initialized at all.
I think it might make more sense to change your constructor to take separate arguments instead of one string that has to be split up.
public Magician(String name, String levels, String supplies, int gallons, double health) {
this.name = name;
this.levels = levels;
...
}
Notice the prefix "this." which prevents name conflicts between the member variables of the class and the parameters passed to the constructor.
i have a school assignment which requires me to add an unknown number of instances of a class "fruit" in to an arraylist "basket" and print out the details of each fruit object, my code adds the fruits to the arraylist but seems to override the previous entry each time leaving me with an arraylist of the same project. This is my code so far:
import java.util.*;
public class Question1
{
public static void main(String[]Augs)
{
List<Fruit> basket = new ArrayList<Fruit>();
int input;
Scanner inp = new Scanner(System.in);
String name;
String colour;
double mass;
int k = -1;
while (true)
{
System.out.println("Enter option: (1) add fruit (2) quit:");
input = inp.nextInt();
if (input==2)
break;
else
{
k++;
System.out.println("Enter name, colour and mass in kg separated by space");
name = inp.next();
colour = inp.next();
mass = inp.nextDouble();
Fruit temp = new Fruit(name, colour, mass);
basket.add(temp);
}
}
for (int i = 0; i<basket.size(); i++)
{
System.out.println(basket.get(i));
}
}
}
//fruit class
public class Fruit
{
private String name;
private String colour;
private double mass;
public Fruit(String name, String colour, double mass)
{
this.name=name;
this.colour=colour;
this.mass=mass;
}
public String toString()
{
return name + " " + colour + " " + mass;
}
}
Your code looks just fine in terms of adding the fruits to the basket. I think what's getting you is System.out.println(basket.get(i)). You are essentially asking a Fruit object to be printed, but the run time does not know how to do that and as such tries to convert the Fruit to some String representation by calling the toString() method on it. I think your Fruit class prints the same String no matter what's inside it. Try overriding the toString() method to get the correct results.
public class Fruit
{
#Override
public String toString()
{
return this.getName() + " " + this.getColor() + " " + this.getMass();
}
}
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.