Java: Error for no reason [closed] - java

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.

Related

How to make private hashmap in one class visible to other class [closed]

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.

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

How do I create a class designated to store an array, and then call it from any other method?

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?

Restaurant Menu: how to efficiently implement a nested loop to collect user input and conduct error checking

I have these two methods which I cant quite figure out the best way to go about their algorithm.
I am writing a program that acts like a restaurant menu and collects user order.
The implementation is,
welcome user and present him with the menu
while the user has not entered 'q', send the user input to a method called getGoodOrderLine(String str)
this method will then check the input for the following,
- First, it must check that a number is present before trying to read it; if there is no number, the entry is an error unless it starts with ‘q’ or ‘Q’, which tells the program to quit.
- then, determine which item the user is asking for by looking at just the first letter. So an input “2 Hello” means 2 hamburgers. the assumption is that if there is a digit in the string, the digit appears before the word, for simplicity
- finally, if the first letter is not (H,C,F or D), print an error message and ask that it be re-entered.
My problem is that, I created a while loop that should loop until the user input is valid, but it doesn't seem to be working, here is my code:
import java.util.*;
public class MenuApp
{
//global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
public static void main(String [] args)
{
//variables
String order;
double total = 0.0;
boolean stopLoop;
//print welcome message && collect order
welcomeCustomer();
order = collectItem();
order = getGoodOrderLine(order);
stopLoop = order.equalsIgnoreCase("q");
while(!stopLoop)//while user hasnt typed q
{
if(order.equalsIgnoreCase("q"))
{
break;
}
order = getGoodOrderLine(order);
//will add the value of user order to total here if order is valid
//leave loop if useer inputs q
}
//ending program
Date today = new Date();
System.out.println("Date: " + today);
System.out.println("Please pay " + total + "\n");
System.out.println("End of processing");
}
public static void welcomeCustomer()
{
System.out.println("Welcome to QuickieBurger!");
System.out.println("Hamburgers \t\t $" + HAM);
System.out.println("cheeseBurgers\t\t $" + CHEESE);
System.out.println("Fries\t\t\t $" + FRIES);
System.out.println("Drinks\t\t\t $" + DRINKS+"\n");
}
public static String collectItem()
{
String userInput = null;
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
System.out.println(userInput);
return userInput;
}
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
if(userInput.equalsIgnoreCase("q"))
{
return userInput;//early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
{
if(Character.isDigit(c))
{pass = true;}
}
//if it doesn't have a digit || string doesnt begin with a digit
if(!Character.isDigit(userInput.charAt(0)))
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
}
else
{
//do the remaining tests here
}
return result;
}
}
I keep getting null pointer and index out of bounds exceptions when testing for Character.isDigit(userInput.charAt(0));
the problem is you are returning empty string so charAt(0) give error since char array has no elements.and if you want to collect items you need to use a collection type like list and u can't use a array since array has fixed length.and to get price of user input product you need to map prices with product names .so u can use map.but i used 2 arrays which act as a map.check this and it's output.
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Scanner;
public class myMenu {
public static String names[] = {"HAM", "CHEESE", "FRIES", "DRINKS"};
public static double prices[] = {3.75, 4.10, 2.50, 1.75};
public static ArrayList<List<String>> allitems = new ArrayList<>();
static double total = 0.0;
public static void main(String[] args) {
welcomeCustomer();
collectItem();
}
public static void welcomeCustomer() {
System.out.println("Welcome to QuickieBurger!");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + "\t\t\t" + prices[i]);
}
}
public static void collectItem() {
String userInput = "";
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
while (!getGoodOrderLine(userInput)) {
userInput = kbd.nextLine();
}
}
private static boolean getGoodOrderLine(String userInput) {
if (userInput.equalsIgnoreCase("q")) {
transaction();
} else if (!Character.isDigit(userInput.charAt(0))) {
System.out.println("quesntity should be specified. try again");
return false;
} else {
for (int i = 0; i < names.length; i++) {
String items = names[i];
//get the first charactor from userinput
char c = 0;
for(int z=0;z<userInput.length();z++){
c=userInput.charAt(z);
if(Character.isAlphabetic(c)){
break;
}
}
if (Character.toLowerCase(items.charAt(0)) ==Character.toLowerCase(c)) {
String s="";
int x=0;
while(Character.isDigit(userInput.charAt(x))){
s+=userInput.charAt(x);
x++;
}
int quentity=Integer.parseInt(s);
double pri = prices[i];
double sub = quentity * pri;
total += sub;
ArrayList<String> subitem = new ArrayList<>();
subitem.add(items);
subitem.add(String.valueOf(quentity));
subitem.add(String.valueOf(sub));
allitems.add(subitem);
return false;
}
}
System.out.println("this not a valid food item.try again");
}
return false;
}
private static void transaction() {
//ending program
Date today = new Date();
System.out.println("-------------------------------------");
System.out.println("Date: " + today);
for (List<String> menu : allitems) {
System.out.println(menu.get(0)+" "+menu.get(1)+" = "+menu.get(2));
}
System.out.println("Please pay " + total + "\n");
System.out.println("------------------------------------");
System.out.println("End of processing");
}
}
output>>
Welcome to QuickieBurger!
HAM 3.75
CHEESE 4.1
FRIES 2.5
DRINKS 1.75
Please place your order (e.g., 3 ham). Enter Q to quit.
2 Hello
4 CHEESE
q
-------------------------------------
Date: Sun Nov 02 02:59:56 PST 2014
HAM 2 = 7.5
CHEESE 4 = 16.4
Please pay 23.9
------------------------------------
End of processing
public class MenuApp
{
// global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
// you need to define errors
public static String noInput = "__MENUAPP_ERROR_1";
public static String invalidInput = "__MENUAPP_ERROR_2";
...
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
boolean startWithDigit = false;
// add this line to verify the input first
if (userInput == null || userInput.equalsIgnoreCase(""))
{
return MenuApp.noInput ;
}
if(userInput.equalsIgnoreCase("q"))
{
return "q"; // early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
if(Character.isDigit(c))
pass = true;
startWithDigit = Character.isDigit(userInput.charAt(0));
// if it doesn't have a digit || string doesnt begin with a digit
if(!startWithDigit)
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
return MenuApp.invalidInput;
}
else
{
// do the remaining tests here
}
return result;
}
}

How do i use the return statement of one method in another private method?

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.

Categories