Validate a course code using a method in java - java

I have to get my course code to validate. The course code is set to a number 1-7 and the choice has to be within this range. Each course is worth 3 credits. The user can not register for more than 9 credits. The user can not register for the same course more than once. I am having trouble with the repeat course code.
Here is my code:
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
public class U6A1_ConsoleRegisterForCourse {
public static void main(String[] args) {
System.out.println("Quenten's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int ValidateChoice;
if ((choice < 1) || (choice >= 8)){
ValidateChoice = -1;}
else if (secondChoice == firstChoice){
ValidateChoice = -2;}
else
{ValidateChoice = 0;}
return ValidateChoice;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
The ValidateChoice method is what I am working on. This is for an academic assignment.

It is better to get rid of those firstChoice, secondChoice, thirdChoice variables and use a homogeneous collection instead:
package u6a1_consoleregisterforcourse;
import java.util.*;
public class U6A1_ConsoleRegisterForCourse {
public static final int CREDITS_PER_COURSE = 3;
public static final int MAX_CREDITS = 9;
public static final int MAX_COURSES = MAX_CREDITS / CREDITS_PER_COURSE;
private final List<Integer> registeredCourses = new ArrayList<>(MAX_COURSES);
private int totalCredit;
public static void main(String[] args) {
System.out.println("Quenten's Copy");
U6A1_ConsoleRegisterForCourse registrar = new U6A1_ConsoleRegisterForCourse();
Scanner input = new Scanner(System.in);
//choice is the current menu selection
int choice;
String yesOrNo;
do {
choice = getChoice(input);
switch (registrar.validateChoice(choice)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registered for this " + choiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than " + MAX_CREDITS + " credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + choiceToCourse(choice));
registrar.totalCredit += CREDITS_PER_COURSE;
registrar.registeredCourses.add(choice);
break;
}
registrar.writeCurrentRegistration();
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
private static final String[] courses = {"IT4782", "IT4784", "IT4786", "IT4789", "IT2230", "IT3345", "IT3349"};
public static String choiceToCourse(int choice) {
return courses[choice - 1];
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
for (int i = 1; i <= courses.length; i++)
System.out.format("[%d]%s%n", i, choiceToCourse(i));
System.out.print("Enter your choice : ");
return (input.nextInt());
}
// This method validates the user menu selection
// against the given registration business rules
// it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public int validateChoice(int choice) {
if ((choice < 1) || (choice > courses.length))
return -1;
if (registeredCourses.contains(choice))
return -2;
if (totalCredit + CREDITS_PER_COURSE > MAX_CREDITS)
return -3;
return 0;
}
public void writeCurrentRegistration() {
StringBuilder sb = new StringBuilder("Current course registration: ");
if (registeredCourses.isEmpty())
sb.append(" { none }");
else {
sb.append("{ ");
boolean first = true;
for (int i : registeredCourses) {
if (first)
first = false;
else
sb.append(", ");
sb.append(choiceToCourse(i));
}
sb.append(" }");
}
System.out.println(sb);
}
}

You need to write 3 different validations in your code:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
//Validation: Choice is in range of 1 and 7
if(choice > 7 || choice < 1){
return -1;
}
// Validation : No 2 course choices have same value
boolean isInvalid = firstChoice!=0 ?
(firstChoice == secondChoice ||firstChoice == thirdChoice):
(secondChoice!=0 && secondChoice==thirdChoice);
if(isInvalid) {
return -2;
}
// Validation : Total credits are not more than 9
else if(totalCredit > 9){
return -3;
}
else{
return 0;
}
}
One of your fellow course mate have also asked this question here,
Validating inputs in a function in java to avoid duplicate data other than non entry with default of 0 (No database )
Be careful of Plagiarism

With the parameters I was given, and only allowed to change the ValidateChoice method, I was able to take John McClane's answer and convert it to make it work. I thank you for the help. What I have done is simple and now makes sense.
Here it is:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
if ((choice < 1) || (choice >7))
return -1;
if ((choice == secondChoice) || (choice == firstChoice))
return -2;
if (totalCredit >= 9)
return -3;
return 0;
}

Related

Output Problems of program

I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:
Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);

How to validate the selection menu using a loop

Can someone edit my code to make it loop the selection menu. If the choice is not one of the 5 options it will prompt the user to re-enter until it is a valid option. If possible an explanation would be helpful as well. Thanks
Here is my code.
import java.util.*;
public class ShapeLoopValidation
{
public static void main (String [] args)
{
chooseShape();
}
public static void chooseShape()
{
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
//while (true) {
if (shapeChoice >= 1 && shapeChoice <=4)
{
if (shapeChoice == 1)
{
circle();
}
else if (shapeChoice == 2)
{
rectangle();
}
else if (shapeChoice == 3)
{
triangle();
}
else if (shapeChoice == 4)
{
return;
}
}
else
{
System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
}
}
class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
}
First: take a look at switch
Second: read a bit about do-while loops (they are usually a good fit for this kind of situations).
Now, how I would implement it (but you should really learn how to make a loop in this scenarios):
public static void chooseShape () {
boolean valid = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
switch (shapeChoice) {
valid = true;
case 1:
circle();
break;
case 2:
rectangle();
break;
case 3:
triangle();
break;
case 4:
return;
default:
valid = false;
System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
System.out.println("Please select one that exists.")
}
} while (!valid)
}
Use do-while flow control until EXIT code entered:
int shapeChoice;
do {
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
// then use if-else or switch
} while (shapeChoice != 4);
OR
use break statement to loop break at your code as bellow:
else if (shapeChoice == 4)
{
break;
}

Java - How to contain a switch statement menu in a while loop

I have a main menu class which gets a choice from the user and then uses that choice to select other classes from a switch statement pertaining to the menu options. My code is:
public static void main(String[] args) {
int dieOne = 0;
int dieTwo = 0;
int choice = 0;
DiceMaker dice = new DiceMaker(); // class that creates the dice
RollDice roll = new RollDice(); // class that imitates roll
DiceMenu menu = new DiceMenu();
DiceRoller series = new DiceRoller();
System.out.println("Welcome to the Dice Roll Stats Calculator!\n");
while (choice != 4) {
menu.DiceMenu();
choice = menu.getUserChoice();
switch (choice) {
case 1:
dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dice.DieOne() + dice.DieTwo());
return;
case 2:
roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
return;
case 3:
series.diceRoller();
series.displayResults();
return;
case 4:
break;
}// switch (choice)
} // while (choice != 4)
}
Case for is the 'Exit' option, so I put the switch statement in a while loop with the boolean condition being not equal to 4 so that when the choice was set to 4 the loop would stop. The proper case executes but the problem I'm having is that the loop, and consequently the program stop after each case that I try, even if the choice was not 4. I tried using break statements after case 1, 2 and 3 as well, and when I did that, it would just repeat the case in an infinite loop. I tried to figure this out on my own cut could never find anything that resembled what I was seeing enough for me to figure out what the problem was. I'm guessing this probably isn't the best way to make a menu in the future. Thank in advance.
The rest of my code is as follows. Please note, DiceRoller class is still under construction, but DiceMaker and RollDice classes seem to be working.
DiceMenu class:
public class DiceMenu
{
public static final int CHOICE_UNKNOWN = 0;
public static final int CHOICE_MAKE_DICE = 1;
public static final int CHOICE_ROLL_ONCE = 2;
public static final int CHOICE_SERIES_ROLL = 3;
public static final int CHOICE_QUIT = 4;
private int choice = 0;
Scanner scan = new Scanner(System.in);
public int DiceMenu()
{
while ( this.choice < 1 || this.choice > 4 ) // while loop keeps choices in range
{
System.out.println(" MAIN MENU\n");
System.out.println("1. Create Your Dice");
System.out.println("2. Roll Your Dice");
System.out.println("3. Perform A Series Of Rolls And Show Stats");
System.out.println("4. Exit\n");
try // avoid invalid input
{
System.out.print("Please choose an option: ");
this.choice = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if ( this.choice < 1 || this.choice > 4 ) // if input is out of range
// notify user before continuing
{
System.out.println("Choice must reflect menu options. (1-4)"
+ " Please try again.\n");
this.choice = 0;
}
}//while ( this.choice < 1 || this.choice > 4 )
return 0;
}
public int getUserChoice()
{
return this.choice;
}
}
RollDice class:
public class RollDice
{
private int roll;
private int rollOne;
private int rollTwo;
private int rollTotal;
public int rollDice (int dieOne, int dieTwo)
{
this.rollOne = 1 + (int)(Math.random() * dieOne);
this.rollTwo = 1 + (int)(Math.random() * dieTwo);
this.rollTotal = this.rollOne + this.rollTwo;
return 0;
}
public void displayRoll()
{
System.out.println("You roll a " + rollOne + " and a "
+ rollTwo + " for a total of " +
rollTotal + "!"); //display separate and total
//roll amounts
if ( rollTotal == 2 ) // if/else tests for special rolls
{
System.out.println("Snake Eyes!");
}
else if ( rollTotal == 7 )
{
System.out.println("Craps!");
}
else if ( rollOne == 6 && rollTwo == 6 )
{
System.out.println("Boxcars!");
}
}
}// public class DiceRoller
DiceMaker class:
public class DiceMaker
{
private int sides = 0;
private int dieOne;
private int dieTwo;
public int diceMaker()
{
while ( sides < 4 || sides > 20 ) // while loop keeps sides within range
{
Scanner scan = new Scanner(System.in);
try // avoid invalid input
{
System.out.print("Please enter the number of sides each die "
+ "should have (must be between 4 and 20): ");
this.sides = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if (sides < 4 || sides > 20) // if input is out of range
// notify user before continuing
{
System.out.println("Die must have between 4 and 20 sides."
+ " Please try again.\n");
}
}//while ( sides < 4 || sides > 20 )
this.dieOne = sides;
this.dieTwo = sides;
return 0;
}
public int DieOne()
{
return this.dieOne;
}
public int DieTwo()
{
return this.dieTwo;
}
}// public class DiceMaker
Remove the return(s) from cases 1,2 and 3. If you return from main the program terminates. You want to loop so don't do that. However, as pointed out by #ajb in the comments below, you don't want the case(s) to fall through. So you need break(s).
case 1: dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dieOne + dieTwo);
// return;
break; // <-- applies to innermost block (switch).
case 2: roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
// return;
break; // <-- applies to innermost block (switch).
case 3: series.diceRoller();
series.displayResults();
// return;
break; // <-- applies to innermost block (switch).
Also, you could use continue (here, which would apply to the innermost loop). Finally, remember that case 4 terminates the loop (because choice is 4) and you don't need case 4 for that reason.

String sentinel on integer input Java

I already posted the question about my example, it was different problem. I came up to another problem. When i choose option 3(multiply) i get result to be zero. And if i choose option 4, cannot divide by zero(zero is my sentinel). How can i make sentinel to be string or char when i use int to input numbers to be calculated? Here is the code.
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int result = 0;
int option;
boolean quit = true;
String done = "";
do {
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while (quit) {
switch (option) {
case 1:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result += numbers;
break;
case 2:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = numbers - result;
break;
case 3:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result *= numbers;
break;
case 4:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = result / numbers;
break;
}
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
} while ("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
Your main problem was that you have initialized result to zero, and it's a good approach for addition and subtraction, but when it comes to multiplication it is not going to work. So, as a solution for that problem you have to set the variable as an Integer, so you can change it as you want inside the loop depending on what operation you are trying to do. Also, it's better because the class Integer allows you to assign its variable to null, which can be so handy in this kind of situations(e.g. better than using 0). Another problem you had was the way you declared an end of your current operation and get the result back. You used 0 as a way of stoping your loop, however, 0 can be used as a number within your calculation. Therefore, you should scan the input as a string then if the user entered = sign, the loop ends and it gives back the result. Then, you can also use the feature that is given to us by the Integer class which allows us to parse integer from a string and use them as regular numbers. Along with that, you had some syntax "errors" and declarations that you could've come with a better way of writing it.
In overall, if you wanted to make a real calculator, this is absolutely not the best approach to do it, because you may face many mathematical problems and exceptions, but its not very bad as a start.
This fix most of your problems:
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
String number;
String process = "";
Integer result = null;
int option = 0;
boolean startOver = true;
while (true) {
Scanner scan = new Scanner(System.in);
if (startOver) {
System.out.print("CALCULATOR MENU" + "\n"
+ "****************" + "\n"
+ "1. Add" + "\n"
+ "2. Substract" + "\n"
+ "3. Multiply" + "\n"
+ "4. Divide" + "\n"
+ "****************" + "\n"
+ "Enter your option >> ");
option = scan.nextInt();
}
switch (option) {
case 1:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ + \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
} else {
result = result + Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
}
case 2:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[- \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
} else {
result = result - Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
}
case 3:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ * \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
} else {
result = result * Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
}
case 4:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ / \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
} else {
result = result / Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
}
}
System.out.println("The result of " + process.replace("+ 0 ", "") + result);
System.out.print("Back to main menu? [y/n]: ");
if (scan.next().equalsIgnoreCase("y")) {
process = "";
result = null;
startOver = true;
} else if (scan.next().equalsIgnoreCase("n")) {
System.out.println("Thank you for using calculator.");
break;
} else {
System.out.println("Wrong input!");
break;
}
}
}
}

I need help with an assignment

I have been working on this programming for about 3 week now and can not figure out my mistakes. I have to use two public classes: 1) validateLength(Number) and 2) convertIntegerToWords(Number). My problem is that once the user inputs their integer my loop continues on forever. The system will ask for an integer, user input, system out either too long or continue on to convertIntgerToWords. My code is below
import java.util.Scanner;
public class Project2 {
public static void main(String [] args) {
//Main Method//
//Create a Scanner//
Scanner input = new Scanner(System.in);
//Enter an Integer//
System.out.print(" What is your integer ? ");
int Number= input.nextInt();
while (Number >= 0) {
if (Number != 0)
validateLength(Number);
else if(Number == 0) {
System.out.print( "Thank you for playing! " + "Good bye! ");
break;
}
}
}
//Next Method//
public static boolean validateLength(int userNum) {
String Number = "" + userNum;
while (userNum >= 0) {
if (userNum < 10)
convertIntegerToWords(userNum);
else if (userNum > 9){
System.out.print("Your integer is too long !");
break;
}
}
}
//End of validate//
//Final Method//
public static String convertIntegerToWords(int Number) {
if (Number == 1)
System.out.println("Your integer " + Number + "is written out as one");
else if (Number == 2)
System.out.println("Your integer " + Number + "is written out as two");
else if (Number == 3)
System.out.println("Your integer " + Number + "is written out as three");
else if (Number == 4)
System.out.println("Your integer " + Number + "is written out as four");
else if (Number == 5)
System.out.println("Your integer " + Number + "is written out as five");
else if (Number == 6)
System.out.println("Your integer " + Number + "is written out as six");
else if (Number == 7)
System.out.println("Your integer " + Number + "is written out as seven");
else if (Number == 8)
System.out.println("Your integer " + Number + "is written out as eight");
else if (Number == 9)
System.out.println("Your integer " + Number + "is written out as nine");
return Number + "";
}
}
}
You need to move
Number = input.nextInt();
inside of the while loop. Here's the typical idiom (other cleanup added as well):
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Enter an Integer//
System.out.print(" What is your integer ? ");
int Number;
while ((Number = input.nextInt()) >= 0)
{
if (Number == 0)
{
System.out.print("Thank you for playing! " + "Good bye! ");
break;
}
validateLength(Number);
}
}
Edit
if the user enters 0 then yes the program terminates. However if the user enters an integer 1-9, the program should spell out the integer in words (ie 1 is written out as one). It does this but it loops infinite. Same as if the user enters an integer larger than 9 it reports that the "YOur integer is too big, enter another integer" This however, repeats on the same line over and over.
That's because of the while loop in validateLength(). Try this out (note the other code cleanup as well):
public class ScannerDemo
{
private static void convertIntegerToWords(int num)
{
String message = null;
if (num > 9)
{
message = "Your integer is too long!";
}
else if (num > 0)
{
message = "Your integer " + num + " is written out as ";
String numString = "";
switch (num)
{
case 1:
numString = "one"; break;
case 2:
numString = "two"; break;
case 3:
numString = "three"; break;
case 4:
numString = "four"; break;
case 5:
numString = "five"; break;
case 6:
numString = "six"; break;
case 7:
numString = "seven"; break;
case 8:
numString = "eight"; break;
case 9:
numString = "nine"; break;
}
message += numString;
}
System.out.println(message);
}
private static int getNextNumber(Scanner s)
{
System.out.println("What is your integer?");
return s.nextInt();
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
while ((number = getNextNumber(input)) >= 0)
{
if (number == 0)
{
System.out.println("Thank you for playing! Good bye!");
break;
}
convertIntegerToWords(number);
}
}
}
It's also on github.
your while conditional is always satisfied, so it will continue to go through the while loop. It will only stop when Number is no longer greater than or equal to zero.
you need to use some other sort of condition entirely, if you want to use a loop (although I cannot tell why you want to in this example). You are never changing the value associated with Number, so it will always be whatever it was instantiated as. Maybe you meant to have code that changes its value given a certain condition? If not, you need to lose that condition entirely.
while (Number >= 0) {
Is creating a while loop, where inside I do not see you decreasing your Number integer to stop the loop. Do you need to use a loop here? You should try an if statement instead.
Also, you may want to consider a switch statement instead of if for the output.
Welcome to StackOverflow.
I feel need to mention you have one class Project2 and two methods not classes. You get an int not an integer and you fail to read the next line which I suspect is your problem, unless you expect the user to type everything on the first line.
I suggest you learn to use a debugger as this can be very useful in finding debugs and understanding what your program is doing. esp for loops which don't end.
//Main Method//
public static void main(String [] args) {
//Create a Scanner//
Scanner input = new Scanner(System.in);
bool bPlay = true;
while (bPlay) {
//Enter an Integer//
System.out.print(" What is your integer ? ");
int Number= input.nextInt();
if (Number != 0)
validateLength(Number);
else if(Number == 0) {
System.out.print( "Thank you for playing! " + "Good bye! ");
bPlay = false;
break;
}
}
}
public static boolean validateLength(int userNum) {
String Number = "" + userNum;
while (userNum >= 0) {
if (userNum < 10)
convertIntegerToWords(userNum);
else if (userNum > 9){
System.out.print("Your integer is too long !");
break;
}
}
This code is responsible of the problem, you never assign userNum a new value but loop while userNum>0. This make a sweet spot for an infinite loop for number >=0 and <10. (you leave the loop ony for number>9).

Categories

Resources