Java number guessing game, while-loop - java

I am making a guessing game which makes a random number between 1 and 200. Whenever I guess, the program will tell me if its too high or too low, then ask me to try again.
I'm supposed to put a "try again" input box inside my code. Now my code is only showing "your guess is too high/too low". I don't understand where and how to put it.
This is my code:
import static javax.swing.JOptionPane.*;
class Tallspill {
public int nyttTall() {
int tilfeldig = (int) (Math.random() * 201);
return tilfeldig;
}
public void visMelding(String melding) {
showMessageDialog(null,melding);
}
private void forLite(int tall) {
if (tall < nyttTall()) {
String melding = (tall + " er for lite. Prøv igjen!");
visMelding(melding);
}
}
private void forStort(int tall) {
if (tall>nyttTall()) {
String melding = (tall+" er for stort. Prøv igjen!");
visMelding(melding);
}
}
public void avsluttRunde(int antall, int tall) {
String melding = (tall + "er riktig. Du brukte " + antall + " forsøk.");
visMelding(melding);
}
public void kjørspill() {
int random = nyttTall();
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
int antall = 0;
while(tall != random) {
if (tall < random) {
forLite(tall);
//metode for nytt forsøk
}
antall++;
if (tall > random) {
forStort(tall);
//metode for nytt forsøk
}
antall++;
if (tall == random) {
avsluttRunde(antall,tall);
}
}
}
}
public class Test {
public static void main(String[] args) {
Tallspill spill = new Tallspill();
spill.kjørspill();
}
}
I tried putting an input string inside the while-loop, but then it just looped on "try again". I also tried putting it inside the toolow and toohigh methods, but then I got an error.

The issue in your solution.
After number is big or small you do not show the number input dialog again. Because that code is outside your while loop
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
I have refactored your code a bit.
public void kjørspill() {
int random = nyttTall();
int tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
int antall = 0;
while(tall != random) {
antall++;
if (tall < random) {
forLite(tall);
tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
//metode for nytt forsøk
} else if (tall > random) {
forStort(tall);
tall = Integer.parseInt(showInputDialog("Skriv inn et tall mellom 0 og 200"));
//metode for nytt forsøk
}
}
avsluttRunde(antall,tall);
}

In your Numbergame class, the tooSmall() and tooBig() methods are always comparing against a new random number. The random number should be a class member variable that gets filled by the newNumber() method, for example:
public class Numbergame {
int randomNumber;
public int newNumber() {
this.randomNumber = (int) (Math.random() * 201);
return randomNumber;
}
private void tooSmall(int number) {
if (number < randomNumber) {
String message = (number + " is too low. Try again!");
showMessage(message);
}
}
private void tooBig(int number) {
if (number > randomNumber) {
String message = (number + " is too high. Try again!");
showMessage(message);
}
}
// rest of class code ...
Here is the entire class reworked. I have also added some input validation so to perhaps eliminate at least some obvious exceptions:
public class Numbergame {
int randomNumber;
public int newNumber() {
this.randomNumber = (int) (Math.random() * 201);
return randomNumber;
}
public void showMessage(String message) {
showMessageDialog(message);
}
private void tooSmall(int number) {
if (number < randomNumber) {
String message = (number + " is too low. Try again!");
showMessage(message);
}
}
private void showMessageDialog(String message) {
JOptionPane.showMessageDialog(null, message, "Just so you know...", JOptionPane.INFORMATION_MESSAGE);
}
private String showInputDialog(String message) {
return JOptionPane.showInputDialog(null, message, "User Input...", JOptionPane.QUESTION_MESSAGE);
}
private void tooBig(int number) {
if (number > randomNumber) {
String message = (number + " is too high. Try again!");
showMessage(message);
}
}
public void endRound(int tries, int number) {
String message = (number + " is CORRECT!. You used " + tries + " tries.");
showMessage(message);
}
public void playgame() {
int random = newNumber();
int tries = 0;
int number = -1;
while (number != random) {
tries++;
String userVal = "";
while (userVal.isEmpty()) {
userVal = showInputDialog("<html>Enter a number between "
+ "<font size='4' color=blue>0</font> and <font size='4' "
+ "color=blue>200</font>:<br><center><font color=gray>('q' "
+ "to quit)</font></center><br></html>");
if (userVal == null || userVal.isEmpty()) {
JOptionPane.showMessageDialog(null, "<html>You must enter <font size='4'>"
+ "<b>something!</b></font></html>",
"Invalid Entry!", JOptionPane.WARNING_MESSAGE);
userVal = "";
}
else if (userVal.equalsIgnoreCase("q")) {
if (JOptionPane.showConfirmDialog(null, "Are you sure you want to Quit?",
"Quit Application?", JOptionPane.YES_NO_OPTION) == 0){
System.exit(0);
}
else {
userVal = "";
}
}
else if (userVal.matches("\\d+")) {
number = Integer.parseInt(userVal);
if (number < 0 || number > 200) {
JOptionPane.showMessageDialog(null, "Invalid Entry! ("
+ number + ")Try again...", "Invalid Entry!",
JOptionPane.WARNING_MESSAGE);
userVal = "";
}
}
}
if (number < random) {
tooSmall(number);
}
else if (number > random) {
tooBig(number);
}
else if (number == random) {
endRound(tries, number);
}
}
}
}
And of course....to play the game:
Numbergame play = new Numbergame();
play.playgame();

Ask user inside infinite while block and exit if user canceled or guessed the number. Check if input number is correct. Remove over checking from Tallspill class methods.
import static javax.swing.JOptionPane.showInputDialog;
import static javax.swing.JOptionPane.showMessageDialog;
class Tallspill {
public int nyttTall() {
int tilfeldig = (int) (Math.random() * 201);
return tilfeldig;
}
public void visMelding(String melding) {
showMessageDialog(null, melding);
}
private void forLite(int tall) {
String melding = tall + " er for lite. Prøv igjen!";
visMelding(melding);
}
private void forStort(int tall) {
String melding = tall + " er for stort. Prøv igjen!";
visMelding(melding);
}
public void avsluttRunde(int antall, int tall) {
String melding = tall + "er riktig. Du brukte " + antall + " forsøk.";
visMelding(melding);
}
public void invalidNumber() {
String melding = "Invalid number. Try again.";
visMelding(melding);
}
public void kjrspill() {
int random = nyttTall();
int tall;
int antall = 0;
while (true) {
antall++;
String tallStr = showInputDialog("Skriv inn et tall mellom 0 og 200");
if (tallStr == null)
return;
try {
tall = Integer.parseInt(tallStr);
if (tall < random)
forLite(tall); //metode for nytt forsøk
if (tall > random)
forStort(tall); //metode for nytt forsøk
if (tall == random){
avsluttRunde(antall, tall);
return;
}
} catch (NumberFormatException ex) {
invalidNumber();
}
}
}
}
public class TestGuessNumber {
public static void main(String[] args) {
Tallspill spill = new Tallspill();
spill.kjrspill();
}
}

Related

Java Sorting Algorithm Classroom Data Structures Project Trouble

I'm having trouble with a project for my Java data structures and algorithms class. I have a classroom program with an option to create, update, display, or see all students.
Can someone help me by implementing a sorting algorithm and explain it? I was trying to sort the students by grade but I don't know how to implement it with a user input.
Here is main:
package main;
import school.School;
public class Main {
public static void main(String[] args) {
School aSchool = new School();
aSchool.initialMenu();
}
}
Here is school:
package school;
import java.io.PrintStream;
import java.util.Scanner;
import student.Student;
public class School {
private final Scanner keyboard = new Scanner(System.in);
private final PrintStream messagePane = new PrintStream(System.out, true);
private int nextAvailablePosition;
private Student[] classroom;
public School() {
super();
}
private void initializeArray() {
classroom = new Student[4];
nextAvailablePosition = 0;
}
private void storeStudentInArray(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.storeStudentInArray()";
if (nextAvailablePosition >= classroom.length) {
Student[] biggerClassroom = new Student[(int) (classroom.length * 1.5)];
System.arraycopy(classroom, 0, biggerClassroom, 0, classroom.length);
classroom = biggerClassroom;
}
classroom[nextAvailablePosition] = aStudent;
nextAvailablePosition++;
}
private Student searchForStudentInArray(String searchID) {
assert searchID != null : "Null parameter supplied to School.searchForStudentInArray()";
int index = 0;
while (index < nextAvailablePosition) {
if (searchID.equalsIgnoreCase(classroom[index].getID())) {
return classroom[index];
}
index++;
}
return null;
}
public void initialMenu() {
initializeArray();
boolean stillWorking = true;
do {
messagePane.print("\n"
+ "WELCOME to the Student Database Organizer 1.0!\n"
+ "Here you can store students in a virtual classroom.\n"
+ "\n"
+ "(C)reates a Student\n"
+ "(U)pdate a Student\n"
+ "(D)isplay a Student\n"
+ "(A)ll Students\n"
+ "(E)nd\n"
+ "Enter Letter Here: \n");
String initialResponse = keyboard.nextLine();
String response = initialResponse.trim().toUpperCase();
if (response.length() > 0) {
response = response.substring(0, 1);
if (response.equals("E")) {
stillWorking = false;
} else if (response.equals("U")) {
updateStudent();
} else if (response.equals("D")) {
displayStudent();
} else if (response.equals("C")) {
Student aStudent = createStudent();
if (aStudent != null) {
storeStudentInArray(aStudent);
}
} else if (response.equals("A")) {
gpa();
} else {
messagePane.println("Try again " + initialResponse
+ ", is not a valid choice.\n"
+ "Please enter one of the letters from the specified menu.");
}
} else {
messagePane.println("You must enter one of the letters from the specified menu\n"
+ "before you press \"Enter\".");
}
} while (stillWorking);
}
private Student createStudent() {
messagePane.println(
"\nYou can enter the student's information here: \n");
messagePane.print("What's the Student's name?: ");
String name = keyboard.nextLine();
messagePane.print("What year/grade is the student?: ");
String agrade = keyboard.nextLine();
messagePane.print("Birthday (MMDDYY): ");
int birthday = keyboard.nextInt();
keyboard.nextLine();
messagePane.print("What's their ID number? (1-7 Numbers): ");
String id = keyboard.next();
keyboard.nextLine();
messagePane.print("Course(s) taken: ");
String course = keyboard.nextLine();
double gpa;
messagePane.print("GPA: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextDouble()) {
gpa = inputScanner.nextDouble();
} else if (inputScanner.hasNext()) {
messagePane.println("You entered something other than a number - the gpa "
+ "has been set to the default of " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
} else {
gpa = Student.DEFAULT_GPA;
}
Student newStudent;
try {
newStudent = Student.create(name,
agrade, birthday, id,
course, gpa );
} catch (Exception anException) {
messagePane.println(" Sorry, I couldn't input the student for you. " + anException.getMessage());
newStudent = null;
}
return newStudent;
}
private void displayStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, this ID number is not in the classroom.");
} else {
messagePane.println(" " + aStudent.getGrade() + " " + aStudent.getName()
+ " (" + aStudent.getBirthday() + ", " + aStudent.getID() + ") " + "\n"
+ " " + aStudent.getCourse() + " GPA: " + aStudent.getGpa()
);
}
}
private void updateStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, the student is not listed.");
} else {
updateMenu(aStudent);
}
}
private void updateMenu(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateMenu()";
String studentBeforeUpdating = singleLineStudentDisplay(aStudent);
messagePane.println("The Student being updated is: \n" + aStudent);
boolean stillTrying = true;
do {
messagePane.print("\n"
+ "Student Database Organizer 1.0\n"
+ "UPDATE MENU OPTIONS\n"
+ ""
+ "Press 1 to change the Student's name\n"
+ "Press 2 to update grade\n"
+ "Press 3 to update course(s)\n"
+ "Press 4 to update gpa \n"
+ "Press 5 to finish updating current Student\n"
+ ""
+ "\nPlease enter your selection: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int response = inputScanner.nextInt();
if (response == 1) {
updateName(aStudent);
} else if (response == 2) {
updateGrade(aStudent);
} else if (response == 3) {
updateCourse(aStudent);
} else if (response == 4) {
updateGpa(aStudent);
} else if (response == 5) {
stillTrying = false;
} else {
messagePane.println(
"You typed " + response + ", which is not a legit option.\n"
+ "Please check the list of numbers in the menu..");
}
} else if (inputScanner.hasNext()) {
String junk = inputScanner.next();
messagePane.println("You entered " + junk + ", which is not a legal option.\n"
+ "Please enter one of the numbers from the specified menu.");
} else {
messagePane.println("Hold your horses! You need to enter a number\n"
+ "before you press \"Enter\".");
}
} while (stillTrying);
messagePane.println("\n" + "Student before updating: " + studentBeforeUpdating);
messagePane.println("Student after updating: " + singleLineStudentDisplay(aStudent));
}
private void updateName(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateName()";
int result;
messagePane.println("The student's name is: " + aStudent.getName());
messagePane.print("Now it is...: ");
String name = keyboard.nextLine();
result = aStudent.setName(name);
messagePane.println("\nUpdate status: "
+ Student.getDescriptionOfReturnedSignal(result) );
messagePane.println("\nFinalized changes: " + singleLineStudentDisplay(aStudent));
}
private void updateBirthday(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateBirthday()";
int result;
messagePane.println("The current birthday is: " + aStudent.getBirthday());
messagePane.print("New birthday (exactly four digits): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int birthday = keyboard.nextInt();
keyboard.nextLine();
result = aStudent.setBirthday(birthday);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " );
} else {
messagePane.println("You didn't enter a number\n"
+ "Please Check the Format MMDDYY \n\n"
+ "Sorry, no changes were made.");
}
}
private void updateGrade(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateGrade()";
int result;
messagePane.println("The student's grade is: " + aStudent.getGrade());
messagePane.print("Now it is... (at least three characters: ");
String agrade = keyboard.nextLine();
result = aStudent.setGrade(agrade);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateCourse(Student aStudent){
assert aStudent != null : "Null parameter supplied to School.updateCourse()";
int result;
messagePane.println("The course(s) taken are: " + aStudent.getCourse());
messagePane.print("Now it is...: ");
String course = keyboard.nextLine();
result = aStudent.setCourse(course);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateGpa(Student aStudent){
assert aStudent != null: "Null parameter supplied to School.updateGpa()";
int result;
messagePane.println("GPA is: " + aStudent.getGpa());
messagePane.print("Now it is... (Must be Postive Number): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
double gpa;
if (inputScanner.hasNextDouble())
{
gpa = keyboard.nextDouble();
}
else
{
messagePane.println("You entered something other than a number - " +
"GPA is back to default " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
}
result = aStudent.setGPA(gpa);
messagePane.println("Update status: " +
Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes" + singleLineStudentDisplay(aStudent));
}
private void gpa() {
int studentCount = nextAvailablePosition;
if (studentCount > 0) {
messagePane.println("\nThe student database has " + studentCount + " student(s):");
messagePane.printf(" %25s, %-35s (%4s, %13s) %-30s %9s \n",
"Grade/Standing", "Student's Name", "Birthday", "ID Number",
"Course(s) taken", "GPA");
int index = 0;
while (index < studentCount) {
Student temp = classroom[index];
messagePane.printf(" %25s, %-35s (%4d, %-13s) %-30s %9.2f \n",
temp.getGrade().length() < 25
? temp.getGrade() : temp.getGrade().substring(0, 25),
temp.getName().length() < 35
? temp.getName() : temp.getName().substring(0, 35),
temp.getBirthday(),
temp.getID(),
temp.getCourse().length() < 30
? temp.getCourse() : temp.getCourse().substring(0, 30),
temp.getGpa());
index++;
}
} else {
messagePane.println("The classroom is currently empty.");
}
}
private Student locateStudent() {
Student aStudent;
messagePane.print("\nEnter the Student's ID you would like to find: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNext()) {
String searchID = inputScanner.next();
aStudent = searchForStudentInArray(searchID);
} else {
messagePane.println("Please enter an ID");
aStudent = null;
}
return aStudent;
}
private String singleLineStudentDisplay(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.singleLineStudentDisplay()";
return aStudent.getGrade() + ", " + aStudent.getName() + " ("
+ aStudent.getID() + ", " + aStudent.getBirthday() + ") "
+ aStudent.getCourse() + " GPA: " + aStudent.getGpa();
}
}
Here is Student :
package student;
public class Student {
public static final int SET_SUCCESSFUL = 0;
public static final int GRADE_CANNOT_BE_NULL = -1;
public static final int GRADE_CANNOT_BE_EMPTY = -2;
public static final int GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS = -3;
public static final int NAME_CANNOT_BE_NULL = -11;
public static final int NAME_CANNOT_BE_EMPTY = -12;
public static final int BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT = -24;
public static final int ID_MUST_BE_ONE_OR_SEVEN_NUMBERS = -31;
public static final int ID_CANNOT_BE_NULL = -32;
public static final int ID_CANNOT_BE_EMPTY = -33;
public static final int COURSE_CANNOT_BE_EMPTY = -41;
public static final int GPA_CANNOT_BE_NEGATIVE = -51;
public static final double DEFAULT_GPA = 0.0;
private String name;
private String grade;
private int birthday;
private String id;
private String course;
private double gpa;
private Student() {
super();
}
public static Student create(String theName,
String theGrade, int theBirthday,String theId,
String theCourse, double theGpa) throws Exception {
Student newStudent = new Student();
int result;
result = newStudent.setName(theName);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGrade(theGrade);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setBirthday(theBirthday);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setId(theId);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setCourse(theCourse);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGPA(theGpa);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
return newStudent;}
// <editor-fold defaultstate="collapsed" desc="------------------------------------------------------------------------------"> /* */
// </editor-fold>
public String getName() {
return name;}
public String getGrade() {
return grade;}
public int getBirthday() {
return birthday;}
public String getID() {
return id;}
public String getCourse() {
return course;}
public double getGpa() {
return gpa;}
#Override
public String toString() {
StringBuilder temp = new StringBuilder(name);
temp.append("\nwho is a ");
temp.append(grade);
temp.append("\nwith a Birthday on ");
temp.append(birthday);
temp.append("\nID Number ");
temp.append(id);
temp.append("\nwho takes ");
temp.append(course);
temp.append("\nwith a GPA of ");
temp.append(gpa);
temp.append(' ');
return temp.toString();
}
public static String getDescriptionOfReturnedSignal(int aSignal) {
if (aSignal == SET_SUCCESSFUL) {
return "SET_SUCCESSFUL";}
if (aSignal == GRADE_CANNOT_BE_NULL) {
return "GRADE_CANNOT_BE_NULL";}
if (aSignal == GRADE_CANNOT_BE_EMPTY) {
return "GRADE_CANNOT_BE_EMPTY";}
if (aSignal == GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS) {
return "GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS";}
if (aSignal == NAME_CANNOT_BE_NULL) {
return "NAME_CANNOT_BE_NULL";}
if (aSignal == NAME_CANNOT_BE_EMPTY) {
return "NAME_CANNOT_BE_EMPTY";}
if (aSignal == BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT) {
return "BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT";}
if (aSignal == ID_CANNOT_BE_NULL) {
return "ID_CANNOT_BE_NULL";}
if (aSignal == ID_CANNOT_BE_EMPTY) {
return "ID_CANNOT_BE_EMPTY";}
if (aSignal == ID_MUST_BE_ONE_OR_SEVEN_NUMBERS) {
return "ID_MUST_BE_ONE_OR_SEVEN_NUMBERS";}
if (aSignal == COURSE_CANNOT_BE_EMPTY) {
return "COURSE_CANNOT_BE_EMPTY";}
if (aSignal == GPA_CANNOT_BE_NEGATIVE) {
return "GPA_CANNOT_BE_NEGATIVE";}
return "Sorry, but the signal value " + aSignal + " is not recognized.";
}
public int setName(String theName) {
if (theName == null) {
return NAME_CANNOT_BE_NULL;
}
String trimmedName = theName.trim();
if (trimmedName.isEmpty()) {
return NAME_CANNOT_BE_EMPTY;
}
name = trimmedName;
return SET_SUCCESSFUL;
}
public int setGrade(String theGrade) {
if (theGrade == null) {
return GRADE_CANNOT_BE_NULL;
}
String trimmedGrade = theGrade.trim();
if (trimmedGrade.isEmpty()) {
return GRADE_CANNOT_BE_EMPTY;
}
if (trimmedGrade.length() < 6) {
return GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS;
}
grade = trimmedGrade;
return SET_SUCCESSFUL;
}
public int setBirthday(int theBirthday) {
if (theBirthday <= 7) {
return BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT;
}
birthday = theBirthday;
return SET_SUCCESSFUL;
}
private int setId(String theId) {
if (theId == null) {
return ID_CANNOT_BE_NULL;
}
String trimmedId = theId.trim();
if (trimmedId.isEmpty()) {
return ID_CANNOT_BE_EMPTY;
}
if (trimmedId.length() != 1 && trimmedId.length() != 7) {
return ID_MUST_BE_ONE_OR_SEVEN_NUMBERS;
}
id = trimmedId;
return SET_SUCCESSFUL;
}
public int setCourse(String theCourse) {
if (theCourse == null) {
course = "";
return SET_SUCCESSFUL;
}
String trimmedCourse = theCourse.trim();
if (trimmedCourse.isEmpty()) {
return COURSE_CANNOT_BE_EMPTY;
}
course = trimmedCourse;
return SET_SUCCESSFUL;
}
public int setGPA(double theGPA) {
if (theGPA < 0.0) {
return GPA_CANNOT_BE_NEGATIVE;
}
gpa = theGPA;
return SET_SUCCESSFUL;
}
/*
public String getbirthday() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
*/
}
Don't have sufficient reputation to comment so adding as answer.
You must remove the current code and specify only the snippets that you tried for 1) Reading the inputs, which I see you are using Scanner 2) What's your approach for sorting
To guide you on this considering this is your classroom program, look at these:
How to read inputs:
How can I read input from the console using the Scanner class in Java?
Comparision:
https://www.baeldung.com/java-comparator-comparable
When should a class be Comparable and/or Comparator?
and then sorting:
https://www.geeksforgeeks.org/collections-sort-java-examples/
https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

variables reverting to default value

I have my program nearly done where their are three classes: one driver class, one pizza class, and an order class that calculates the order price. My only issue is once I run my code the variables will set through the while loop in the inputToppings method of the pizza class and will print the correct values when the toString method is called from the pizza class in the order class but in my getToppingQuantity method it's passing the default values for the instance variables. Where am I going wrong here?
package edu.ilstu;
import java.util.Scanner;
public class Pizza
{
//default pizza is cheese and tomato sauce only
private int alfredo = 0;
private int pesto = 0;
private int tomato = 1;
private int sausage = 0;
private int pepperoni = 0;
private int onion = 0;
private int mushroom = 0;
private int greenPepper = 0;
private int cheese=1;
private char choice;
public int getCheese() {
return cheese;
}
public int getAlfredo()
{
return alfredo;
}
public void setAlfredo()
{
alfredo=1;
pesto=0;
tomato=0;
}
public int getPesto()
{
return pesto;
}
public void setSausage(int sausage)
{
this.sausage = sausage;
}
public void setPepperoni(int pepperoni)
{
this.pepperoni = pepperoni;
}
public void setOnion(int onion)
{
this.onion = onion;
}
public void setMushroom(int mushroom)
{
this.mushroom = mushroom;
}
public void setGreenPepper(int greenPepper)
{
this.greenPepper = greenPepper;
}
public void setCheese(int cheese)
{
this.cheese = cheese;
}
public void setPesto()
{
pesto=1;
tomato=0;
alfredo=0;
}
public int getTomato()
{
return tomato;
}
public void setTomato()
{
tomato=1;
pesto=0;
alfredo=0;
}
public int getSausage()
{
return sausage;
}
public int getPepperoni()
{
return pepperoni;
}
public int getOnion()
{
return onion;
}
public int getMushroom()
{
return mushroom;
}
public int getGreenPepper()
{
return greenPepper;
}
public void inputToppings() {
Scanner sc = new Scanner (System.in);
while (true) {
System.out.println("Input toppings. Enter Q to quit");
System.out.println("1. Sausage");
System.out.println("2. Pepperoni");
System.out.println("3. Onion");
System.out.println("4. Mushroom ");
System.out.println("5. Green Pepper");
System.out.println("6. Cheese");
System.out.println("7. Alfredo");
System.out.println("8. Pesto");
System.out.println("9. Tomato");
if (choice == 'q' || choice == 'Q') {
break;
}
if (choice == '1') {
addSausage();
}
if (choice == '2') {
addPepperoni();
}
if (choice == '3') {
addOnion();
}
if (choice == '4') {
addMushroom();
}
if (choice == '5') {
addGreenPepper();
}
if (choice == '6') {
addCheese();
}
if (choice == '7') {
if(alfredo != 1) {
setAlfredo();
}
else
System.out.println("No double sauce allowed");
}
if (choice == '8'){
if (pesto != 1) {
setPesto();
}
else
System.out.println("No double sauce allowed");
}
if (choice == '9') {
if(tomato != 1) {
setTomato();
}
else
System.out.println("No double sauce allowed");
}
choice = sc.next().charAt(0);
}//end while loop
sc.close();
}//end of inputToppings method
public void addCheese() {
if(cheese<2) {
setCheese(cheese+1);
}
else
System.out.println("Invalid input");
}
public void addPepperoni() {
if (pepperoni<2) {
setPepperoni(pepperoni+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addSausage() {
if(sausage<2) {
setSausage(sausage+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addOnion() {
if(onion<2) {
setOnion(onion+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addGreenPepper() {
if(greenPepper<2) {
setGreenPepper(greenPepper+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addMushroom() {
if(mushroom<2) {
setMushroom(mushroom+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public String toString() {
String str ="sausage = " + Integer.toString(sausage) + " Pepperoni = " + Integer.toString(pepperoni) + "\n" + "Onion = " + Integer.toString(onion) + " Mushroom = " + Integer.toString(mushroom) +"\n" + "cheese = " + Integer.toString(cheese) +"\n" + "Tomato = " + Integer.toString(tomato) + " Pesto = " + Integer.toString(pesto) + " Alfredo = " + Integer.toString(alfredo);
return str;
}
public int getToppingQuantity() {
return sausage+pepperoni+onion+mushroom+cheese;
}
}//end of class
here is the order class
public class Order
{
final double TAX_RATE = 0.075;
final double BASE_PRICE = 5.00;
final double TOPPING_CHARGE = 0.75;
final double DELIVERY_CHARGE = 0.10;
public char typeOfOrder;
public String storeLocation = "";
Pizza pizza1 = new Pizza();
Customer cust1 = new Customer();
public double calculateSubtotal() {
double toppingPrice = (pizza1.getToppingQuantity()*TOPPING_CHARGE);
return BASE_PRICE+toppingPrice;
}
public double calculateSalesTax() {
return calculateSubtotal()*TAX_RATE;
}
public double calculateDeliveryCharge() {
return (calculateSubtotal() + calculateSalesTax()) * DELIVERY_CHARGE;
}
public void displaySummary() {
if (typeOfOrder=='d' || typeOfOrder=='D') {
System.out.printf("Subtotal $%.2f\n", calculateSubtotal());
System.out.printf("Sales Tax: $%.2f\n", calculateSalesTax());
System.out.printf("Delivery Charge: $%.2f\n", calculateDeliveryCharge());
System.out.printf("Total: $%.2f\n", calculateSubtotal() + calculateSalesTax() + calculateDeliveryCharge());
System.out.println(pizza1.getToppingQuantity());
System.out.println("Thank you, come again!");
}
else if (typeOfOrder == 'p' || typeOfOrder == 'P') {
System.out.println(storeLocation);
System.out.printf("Subtotal $%.2f\n", calculateSubtotal());
System.out.printf("Sales Tax: $%.2f\n", calculateSalesTax());
System.out.printf("Total: $%.2f\n", calculateSubtotal() + calculateSalesTax());
System.out.println("Thank you, come again!");
}
}
public char getTypeOfOrder()
{
return typeOfOrder;
}
public void setTypeOfOrder(char typeOfOrder)
{
this.typeOfOrder = typeOfOrder;
}
public String getStoreLocation()
{
return storeLocation;
}
public void setStoreLocation(String storeLocation)
{
this.storeLocation = storeLocation;
}
}
and finally the driver class
public class PizzaDriver
{
public static void main(String[] args) {
Customer cust01= new Customer();
Order order01 = new Order();
Pizza pizza01 = new Pizza();
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to ILSTU Pizza");
System.out.println("Step 1: Is this for a pickup or delivery?");
System.out.println("1 Pickup");
System.out.println("2 Delivery");
int choice = sc.nextInt();
System.out.println("Choice: " + choice);
if (choice==1) {
order01.setTypeOfOrder('p');
System.out.println("1. 207 W. North St, Normal, IL");
System.out.println("2. 208 Landmark Dr, Bloomington, IL");
System.out.println("3. 1600 W. Market St, Bloomington, IL");
System.out.println("Which location would you like to pickup from?");
choice=sc.next().charAt(0);
if (choice=='1') {
order01.setStoreLocation("207 W. North St, Normal, IL");
}
else if (choice=='2') {
order01.setStoreLocation("208 Landmark Dr, Bloomington, IL");
}
else if (choice=='3') {
order01.setStoreLocation("1600 W. Market St, Bloomington, IL");
}
else
System.out.println("invalid choice");
System.out.println("At this stage would you like to quit this order entry process? \n Enter 'Y' to quit or 'N' to continue on to build your pizza.");
choice=sc.next().charAt(0);
if (choice=='N'|| choice == 'n') {
pizza01.inputToppings();
System.out.println("Your pizza contains the following toppings: \n" + pizza01.toString());
order01.displaySummary();
}
else if(choice == 'Y' || choice == 'y') {
System.out.println("Thank you, come again!");
}
}
else if (choice == '2') {
//System.out.println("Step 2: Customer Information");
order01.setTypeOfOrder('d');
sc.nextLine();
System.out.println("Please enter your first and last name: \n");
cust01.setFullName(sc.nextLine());
System.out.println("Please enter your street address");
cust01.setAddress(sc.nextLine());
System.out.println("Please enter your city, state and zip code");
cust01.setCityStateZip(sc.nextLine());
System.out.println("Please enter your phone number (10-dights only)");
String userNumber=sc.nextLine();
while(true) {
if (userNumber.length()==10) {
cust01.setPhoneNumber(userNumber);
break;
}
else if (userNumber.length()!=10) {
System.out.println("Invalid phone number, Enter a valid one");
}
userNumber=sc.nextLine();
}
System.out.println(cust01.toString()+"\n");
System.out.println("At this stage would you like to quit this order entry process? \n Enter 'Y' to quit or 'N' to continue on to build your pizza.");
choice=sc.next().charAt(0);
if (choice=='N'|| choice == 'n') {
pizza01.inputToppings();
System.out.println("\n Your pizza contains the following toppings: \n" + pizza01.toString());
order01.displaySummary();
}
else if(choice == 'Y' || choice == 'y') {
System.out.println("Thank you, come again!");
}
}
else
System.out.println("invalid choice");
}
}
like I said my program goes through the steps properly but returns the wrong value for the topping variables in the getToppingQuantity method (Note: I didn't include the customer class because it doesn't pertain to my current issue)
In your Order class you have a Pizza instance variable, but in your PizzaDriver you're creating and using a different Pizza object. This is likely the root cause of your issues. (You're also doing the same thing with the Customer class.)
This means that
System.out.println("\n Your pizza contains the following toppings: \n"
+ pizza01.toString());
...and...
order01.displaySummary();
Refer to different Pizza objects.
Your while(true) block in inputToppings() will never allow for an exit from the while condition (except in the break you provided to quit. Not that while(true) is an unacceptable programming practice, but it can lead to infinite loops. Better to provide a boolean flag, then exit once the value of the flag has changed.

Validating against duplicate user entries when using sets

I am currently studying Java and have being using normal arrays so far. Next semester we will be using data structures like ArrayList etc, but i decided to read ahead. I have read that for storing data that can not be a duplicate, Sets were the data structure of choice, but in the code below the user can still enter a duplicate entry? Can any body explain the process to me and perhaps a solution to my problem?
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 0;
private static final int MAX_NUMBER_POSSIBLE = 25;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Pick " + INPUT_SIZE + " numbers from "
+ MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ".");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("You win :) !");
} else {
System.out.println("Sorry you failed :( !");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nRandom numbers where : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChoosen = input.nextInt();
if (numberChoosen < MIN_NUMBER_POSSIBLE
|| numberChoosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in "
+ MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE
+ " range.");
} else {
userNumbers.add(numberChoosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been called.");
}
}
Set#add(Object) returns true when the object was added successfully and false otherwise. It will not throw an exception, so you need to add a conditional to check whether the operation was successful:
if (userNumbers.add(numberChoosen)) {
System.out.println("Number added successfully");
} else {
System.out.println("Duplicate number detected");
}
Sets do not prohibit entering a unique value more than once. It is on you to check preconditions, see e.g Set.add.
So instead of just calling:
userNumbers.add(numberChoosen);
try
if (!userNumbers.contains(numberChoosen)) {
userNumbers.add(numberChoosen);
} else {
// do stuff...
}

Credit card type and validation

I would like to run a program that can determine the validation and type of credit card number based of number entered. Compiler shows notification that there is an error in my coding but I cannot detect where is it. The program is also cannot be run. Below is the coding,
import java.util.*;
public class CreditCard {
public static void main(String args[]) {
String CType;(String number) {
if (number.startsWith("4"))
return "Visa";
else if (number.startsWith("5"))
return "MasterCard";
else if (number.startsWith("6"))
return "Discover";
else if (number.startsWith("37"))
return "American Express";
else
return "Unknown type";
};
Scanner input = new Scanner(System.in);
System.out.println("Enter a credit card number: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + (sumOfOddPlaces(number)*2);
if (isValid(total)) {
System.out.println("The "+CType+" card number is valid");
} else {
System.out.println("The "+CType+" card number is invalid.");
}
}
public static boolean isValid(long total) {
if (total % 10 != 0) {
} else {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
number /= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
}
I do card type detection with an enum:
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3}){0,2}$"),
MASTERCARD("^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]\\d|095|6\\d{0,2}|[89]\\d{2})\\d{12,15}$"),
DISCOVER("^6(?:011|[45][0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
You can then do CardType.detect("cardnumbergoeshere") and you'll get back CardType.VISA, etc.
There's a unit test over at the gist.
For validation, I have:
public boolean isValid(String cardNumber) {
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
That should do it.
Edit: fixed escape characters in DINERS_CLUB
This may be more along the lines of what you're trying to do:
public static void main(final String args[])
{
String cType = null;
System.out.println("Enter a credit card number: ");
final Scanner input = new Scanner(System.in);
final String cardNumber = input.next();
if (cardNumber.startsWith("4"))
{
cType = "Visa";
}
else if (cardNumber.startsWith("5"))
{
cType = "MasterCard";
}
else if (cardNumber.startsWith("6"))
{
cType = "Discover";
}
else if (cardNumber.startsWith("37"))
{
cType = "American Express";
}
else
{
cType = "Unknown type";
}
final long total = sumOfEvenPlaces(Long.valueOf(cardNumber)) + (sumOfOddPlaces(Long.valueOf(cardNumber)) * 2);
if (isValid(total))
{
System.out.println("The " + cType + " card number is valid");
}
else
{
System.out.println("The " + cType + " card number is invalid.");
}
}
On a stylistic note, CType should start with a lower case letter (e.g. cType). You'll have to experiment with the use of Scanner as well as I'm not sure my implementation will do what you're looking for.

Sorting highscore by time and number of guesses

As of now my highscore list is only sorted by number of guesses. I would like entries with identical number of guesses to also be sorted by time in ms, in descending order. Tried searching and found some similar Q's but couldn't really find a solution. Any pointers will be greatly appreciated! Feel free to comment on other parts of my code as well!
import java.util.*;
public class Game {
private static ArrayList<highScore> score = new ArrayList<highScore>();
private class highScore implements Comparable<highScore> {
int guessCount = 0;
double playerTime = 0;
String playerName;
public highScore (int guessCount, double playerTime, String playerName) {
this.guessCount = guessCount;
this.playerTime = playerTime;
this.playerName = playerName;
}
public String toString() {
String scoreList = (this.playerName + "\t\t" + this.guessCount + "\t\t" + this.playerTime);
return scoreList;
}
public int compareTo(highScore hs) {
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
return -1;
}
}
public static void main(String [] args) {
boolean playGame = true;
Scanner scan = new Scanner(System.in);
Game g = new Game();
while(playGame) {
g.start();
System.out.println("\nPlay again?");
String s = scan.nextLine();
if (s.equalsIgnoreCase("n")) {
System.out.print("Quitting...");
playGame = false;
}
}
}
public void start() {
int number = (int) (Math.random() * 1001 );
int guess = -1;
int guessCount = 0;
String guessStr, playerName;
String quit = "quit";
Scanner scan = new Scanner(System.in);
boolean play = true;
System.out.print("Welcome to the greatest guessing game of all time!" +
"\nGuess a number between 1-1000!" +
"\nType \"quit\" to quit.");
long startTime = System.currentTimeMillis();
System.out.println("\nDEBUG, nr is: " + number);
while (guess != number && play) {
try {
System.out.print("\nEnter your guess: ");
guessStr = scan.nextLine();
if (guessStr.equalsIgnoreCase("quit")) {
play = false;
System.out.println("Quitting...");
return;
}
guess = Integer.parseInt(guessStr);
if (guess <= 1 || guess > 1000) {
System.out.println("Invalid guess, won't count, try again!");
}
if (guess < number) {
System.out.println("Too low, try again!");
guessCount++;
}
if (guess > number) {
System.out.println("Too high, try again!");
guessCount++;
}
}
catch(NumberFormatException e) {
System.out.println("Sorry, only numbers. Try again!");
}
catch (InputMismatchException ex) {
System.out.println("Sorry, only numbers. Try again!");
}
}
if (guess == number) {
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Nice, the correct number is " + number + "!");
System.out.print("You nailed it after " + (int)(gameTime)/1000 + " seconds and " + guessCount + " tries!");
System.out.println("\nEnter your name!");
playerName = scan.nextLine();
score.add(new highScore(guessCount, gameTime, playerName));
Collections.sort(score);
System.out.println("Name ------- Guesses -------- Time in ms");
for (highScore h: score) {
System.out.println(h);
}
}
}
}
You just need to modify your compareTo method to consider the equality case also. And then move to the next comparison: -
public int compareTo(highScore hs) {
if (this.guessCount == hs.guessCount) {
return (new BigDecimal(this.playerTime)).compareTo(
new BigDecimal(hs.playerTime)
} else {
return Integer.valueOf(this.guessCount).compareTo(
Integer.valueOf(hs.guessCount));
}
}
The compareTo() method of highScore has to be implemented as below
public int compareTo(highScore hs)
{
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
{
if(this.guessCount == hs.guessCount)
{
if(this.playerTime > hs.playerTime)
{
return 1;
}
else
{
return -1;
}
}
return -1;
}
}
- Whenever you need to sort on the basis of more than 1 attributes, go for java.util.Comparator Interface.
- Use the compare() method of Comparator<T> along with Collections.sort(List l, Comparator c) to sort you list.

Categories

Resources