so im very new to programming so sorry if is an inane question
But i have been given a homework where i have to create a transcript with java using array,
first i have to enter the students name and code, then the peogram should tell me to enter each lesson’s grade individually
And the result should display the student’s name,code and the grades i have entered for each lecture
I know how to enter make the program prompt me with each lecture and grade entry but showing all the grades i have entered next to thier lecture is what im stuck on
I would highly appreciate it if i get an answer.
Thanks
Take a look at this code, if there is something obscure, ask for clarification.
MainClass.java class
public class MainClass {
static boolean flag = true;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
//create new student
Student student = new Student();
//print out enter name of a student
System.out.println("Enter name of student: ");
//read students name from next line
student.setNameOfStudent(keyboard.nextLine());
//print out enter code of a student
System.out.println("Enter code of student: ");
//read students password from a next line
student.setPasswordOfStudent(keyboard.nextLine());
//create a list of lectures to add them to a student
List<Lecture> lectures = new ArrayList<>();
//do adding lectures and grades for them while N is not pressed
do {
// enter new lecture name
System.out.println("Add a lecture? Y or N ");
//take answer for adding a lecture from a next input
String answerForAddingLecture = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answerForAddingLecture)) {
// print enter a name of a lecture
System.out.println("Enter a name of a lecture? ");
//take a lecture name from next input
String lectureName = keyboard.next();
// create a lecture
Lecture lecture = new Lecture();
// set lecture name from lectureName variable
lecture.setNameOfLecture(lectureName);
//create a list of grades
List<Grade> listOfGrades = new ArrayList<>();
//do inside brackets while flag is set to true
do {
//print Add a grade for this lecture? Y or N
System.out.println("Add a grade for this lecture? Y or N ");
//set an answer variable from the next input
String answer = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answer)) {
//print what grade is it going to be?
System.out.println("What grade is it going to be?");
//create new grade object
Grade grade = new Grade();
//set temp variable to next int input
int temp = keyboard.nextInt();
//set grade value to the value of temp variable
grade.setGrade(temp);
// add this grade to a list of grades
listOfGrades.add(grade);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answer)) {
//set flag to false
flag = false;
}
}
//do above as long as flag is set to true
while (flag);
//reset flag to true again for keep adding new lectures
flag = true;
//set a list of grades to a lecture grades list
lecture.setGradesOfLecture(listOfGrades);
//set a lecture to a list of lectures
lectures.add(lecture);
//set a list of lectures to a students lecture list
student.setLecturesOfStudent(lectures);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answerForAddingLecture)) {
flag = false;
}
} while (flag);
//print a student with all lectures and grades
System.out.println(student.toString());
}
}
Student.java class
public class Student {
private String nameOfStudent;
private String passwordOfStudent;
private List<Lecture> lecturesOfStudent;
public Student() {
}
public Student(String nameOfStudent, String passwordOfStudent, List<Lecture> lecturesOfStudent) {
this.nameOfStudent = nameOfStudent;
this.passwordOfStudent = passwordOfStudent;
this.lecturesOfStudent = lecturesOfStudent;
}
/**
* #return the nameOfStudent
*/
public String getNameOfStudent() {
return nameOfStudent;
}
/**
* #param nameOfStudent the nameOfStudent to set
*/
public void setNameOfStudent(String nameOfStudent) {
this.nameOfStudent = nameOfStudent;
}
/**
* #return the passwordOfStudent
*/
public String getPasswordOfStudent() {
return passwordOfStudent;
}
/**
* #param passwordOfStudent the passwordOfStudent to set
*/
public void setPasswordOfStudent(String passwordOfStudent) {
this.passwordOfStudent = passwordOfStudent;
}
/**
* #return the lecturesOfStudent
*/
public List<Lecture> getLecturesOfStudent() {
return lecturesOfStudent;
}
/**
* #param lecturesOfStudent the lecturesOfStudent to set
*/
public void setLecturesOfStudent(List<Lecture> lecturesOfStudent) {
this.lecturesOfStudent = lecturesOfStudent;
}
public String getLecturesWithGrades() {
String temp = "\nLectures:";
for (Lecture l : getLecturesOfStudent()) {
temp += "\n" + l.getNameOfLecture();
temp += "\nGrades:\n";
for (Grade g : l.getGradesOfLecture()) {
temp += g.getGrade() + " ";
}
}
return temp;
}
#Override
public String toString() {
return "Student: " + getNameOfStudent() + " with a code: " + getPasswordOfStudent() + getLecturesWithGrades();
}
}
Lecture.java class
public class Lecture {
private String nameOfLecture;
private List<Grade> gradesOfLecture;
public Lecture() {
}
public Lecture(String nameOfLecture, List<Grade> gradesOfLecture) {
this.nameOfLecture = nameOfLecture;
this.gradesOfLecture = gradesOfLecture;
}
public String getNameOfLecture() {
return nameOfLecture;
}
public List<Grade> getGradesOfLecture() {
return gradesOfLecture;
}
public void setNameOfLecture(String nameOfLecture) {
this.nameOfLecture = nameOfLecture;
}
public void setGradesOfLecture(List<Grade> gradesOfLecture) {
this.gradesOfLecture = gradesOfLecture;
}
#Override
public String toString() {
return getNameOfLecture() + " " + getGradesOfLecture();
}
}
Grade.java class
/**
* Might add remarks on grades or any other properties some time later, therefore new
* object is created called Grade.
* #author
*/
public class Grade {
int grade;
public Grade() {
}
public Grade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
#Override
public String toString() {
return getGrade() + " ";
}
}
Related
This is my first time posting on StackOverflow, but I have visited many times. I am taking a computer science class and I ran into a problem that I have not been able to resolve through research. The assignment is to create a NBATeam class with instance variables and constructors and a NBA client that receives parameters of the names of players from the user and passes them to an array in the first class.
So the problem that I ran into is when I run my program, and I enter player names and pass them to the array, the first array of names are deleted. The names entered into the most recent array are fine, however.
I apologize if my terminology is wrong I am still a newb!
Thank you so much for any help you can give me.
I will insert my code below. My problem is where it says [null]. Also I entered bob for the first team and brian for the second team but bob is in the second team's array.
Please help!
Create NBA team of Heats
Add a player to team Heats? (yes/no)
yes
Enter the name of the player:
bob
Add one more player to Heats?
no
Create NBA team of Spurs
Add a player to team Spurs? (yes/no)
yes
Enter the name of the player:
brian
Add another player to Spurs?
no
***Heat Wins!***
Heats[null]Wins: 4 Loses: 0
Spurs[bob]Wins: 0 Loses: 4
import java.util.*;
public class NBA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ifAddPlayer, playerName = null;
//construct Team Heat
System.out.println("Create NBA team of Heats");
NBATeam heats = new NBATeam("Heats");
System.out.println("Add a player to team Heats? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
heats.addPlayer(playerName);
playerName = input.next();
System.out.println("Add one more player to Heats?");
ifAddPlayer = input.next();
}
//construct team Spurs.
System.out.println("Create NBA team of Spurs");
NBATeam spurs = new NBATeam("Spurs");
System.out.println("Add a player to team Spurs? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
spurs.addPlayer(playerName);
playerName = input.next();
System.out.println("Add another player to Spurs?");
ifAddPlayer = input.next();
}
playAGame(heats,spurs);
System.out.println(heats.toString());
System.out.println(spurs.toString());
}
public static void playAGame(NBATeam heats, NBATeam spurs) {
for(int game = 0; game < 7; game++){
double score = Math.random();
if (score < .5) {
heats.winAgame(spurs);
}
else{
spurs.winAgame(heats);
}
if(spurs.nWin()==4 || heats.nWin()==4) {
break;
}
}
if(spurs.nWin()>heats.nWin()) {
System.out.println("***Spurs Win!***");
}
else
System.out.println("***Heat Wins!***");
}
}
import java.util.Arrays;
public class NBATeam {
private String sTeamName;
private int nWin;
private int nLoss;
private int nPlayer;
private String [] playerArray = new String[nPlayer];
public NBATeam(String sTeamName) {
this.sTeamName = sTeamName;
nPlayer=0;
}
public int nWin() {
return nWin;
}
public int nLoss() {
return nLoss;
}
public String getTeamName(){
//gets team's Name
return sTeamName;
}
public String toString() {
return sTeamName + Arrays.toString(playerArray)+ "Wins: " + nWin +
" Loses: " + nLoss;
}
public void lossAgame() {
this.nLoss++;
}
public void winAgame(NBATeam team2) { //To win over the team
nWin++;
team2.setLoss(team2.nLoss()+1);
//teamB.lossAgame();
}
public int getLossNumber() {
return this.nLoss;
}
public void setLoss(int l) {
this.nLoss=l;
}
public int getWinNumber() {
return this.nWin;
}
public void setWin(int w) {
this.nWin=w;
}
public void addPlayer(String player) {
String temp[] = playerArray;
playerArray = Arrays.copyOf(temp, temp.length+1);
playerArray[nPlayer] = player;
nPlayer++;
}
public String[] getPlayerArray() {
return playerArray;
}
public void setPlayerArray(String[] playerArray) {
this.playerArray = playerArray;
}
}
You start with an initial value of null in playerName, and then you add the playerName before getting the value. This,
heats.addPlayer(playerName);
playerName = input.next();
is reversed. It should be
playerName = input.next();
heats.addPlayer(playerName);
And, you were consistent. This,
spurs.addPlayer(playerName);
playerName = input.next();
is likewise reversed. And should be
playerName = input.next();
spurs.addPlayer(playerName);
I would suggest you limit the visibility of your variables. If you had
String playerName = input.next();
heats.addPlayer(playerName);
it would limit the possibility of adding the player before you set it.
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
I have a linked list with objects called ll. My object is called Student which has a name, a grade and an age. I want to create a find method based on the student's name.
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList<Object> ll = new LinkedList<Object>();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
Student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
Student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
Student.setAge(age);
}
public Student findStudent(){
p("Which student do you want to change? Please enter their name:");
String name = s.nextLine();
boolean a=false;
for (int e=0; e<ll.size(); e++) {
if (name.equals(ll(e).name)) {
p("Found the student");
break;
return e;
//Find student in the list - left for the author
} else {
a=true;
}
}
if (a) {
p("Student is not in the list");
Student student = null;
return student;}
}
public String show() {
if (ll!=null) {
for (int i=0; i<ll.size(); i++) {
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
} else {return "There are no students in the list";
}
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
p("What do you want to do?");
Course course = new Course();
p("To add a student press 1");
p("To change the name of a student press 2");
p("To set the grade for a student press 3");
p("To set the age of a student press 4");
p("To find a student press 5");
p("To show the students press 6");
p("To get the age of a student press 7");
p("To get the grade of a student press 8");
int a = s.nextInt();
if (a==1) {
addStudent();
} else if (a==2) {
changeName();
}else if (a==3) {
setGrade();
}else if (a==4) {
setAge();
} else if (a==5) {
findStudent();
}else if (a==6) {
show();
} else if (a==7) {
getAge();
} else if (a==8) {
getGrade();
}
new Course();
}
}
In the find method, it says that it can not find the symbol ll(int). What can i do to make a find method based on a parameter of my Object.
To get the n'th element from a list, use the get method: ll.get(e) instead of ll(e).
On the other hand, you are iterating over the list, and it's more efficient to not call get repeatedly on a linked list. Instead you can do this:
int e = 0;
for (Student s: ll) {
if (name.equals(s.name)) ....
e++;
}
To make the existing method work, you need to change :
if (name.equals(ll(e).name)) {
to
if (name.equals(ll.get(e).name)) {
We need to use get() method to get an element from a list, it's different from an array.
Also, if you want a method to find student by name, you can write one as follows:
public Student findStudent(String name){
for (int e=0; e<ll.size(); e++) {
if (ll.get(e).name.equals(name)) {
return e;
}
}
//Not found
return null;
}
I want to read data from a text file and print the output to both the terminal and a text file. I have a loop that reads for numbers and one that reads for non-numerical characters, but nothing is printing out to the terminal. i am new to programming.
I am transforming an old project to a new one by the way.
package studenttester;
public class Student
{
private String name;
double quizScore;
double quizAverage;
private int numQuizzes;
String grade;
/**
* Returns the name of a student
*
* #return the name of the student
*/
public Student (String inName)
{
name = inName;
quizAverage = 0;
quizScore = 0;
numQuizzes = 0;
}
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* #param score the score of a quiz
*/
void addQuiz(int score)
{
numQuizzes += 1;
quizScore += score;
}
/**
* Returns the total score of all the quizzes combined that student took
*
* #return the value of score
*/
double getTotalScore()
{
return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* #return
*/
double getAverageScore()
{
return quizScore / numQuizzes;
}
}
package studenttester;
import java.io.*;
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Student Name Number of Quizzes Average");
Scanner reader = new Scanner(new File("quizScores.txt"));
String studentName = "", first="", last="";
while (!reader.hasNext("-10"))
{
}
while (reader.hasNextDouble())
{
first = first+reader.next();
studentName = last + first;
}
Student newStudent = new Student(studentName);
while (reader.hasNextDouble() && !reader.hasNext("-10"))
{
System.out.printf("");
}
{
// writer.close;
}
}
}
The "red underline" means an compiler error, I guess.
Have a look to your while loop, it seems to be wrong.
Try ...
while (reader.hasNextDouble() && (!reader.hasNext("-10")))
System.out.printf("");
}
reader.close();
instead.
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;
}
}