I need help with an assignment - java

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).

Related

Continuous Calculator

I'm making a calculator where you ask two numbers and an operation. If the user wants to continue, ask for a number and an operation. Then, perform the selected operation with the recent result and the new input value.
I'm stuck in storing the result of the last operation to use it for another operation. Here's my code
import java.util.Scanner;
public class practice {
static double add, sub, mul, div;
static double another;
public static void main(String[] args) {
char choose, cont;
Scanner u = new Scanner(System.in);
System.out.print("Enter number 1: ");
double one = Double.parseDouble(u.nextLine());
System.out.print("Enter number 2: ");
double two = Double.parseDouble(u.nextLine());
do {
System.out.print("\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose = u.next().charAt(0);
if ((choose == 'A') || (choose == 'a')) {
add = one + two;
add += another;
System.out.println("The sum is " + add);
} else if (choose == 'B' || choose == 'b') {
sub = one - two;
sub -= another;
System.out.println("The difference is " + sub);
} else if (choose == 'C' || choose == 'c') {
mul = one * two;
mul *= another;
System.out.println("The product is " + mul);
} else if (choose == 'D' || choose == 'd') {
div = one / two;
div /= another;
System.out.println("The quotient is " + div);
} else {
System.out.println("Invalid Selection");
}
System.out.print("Continue?[Y/N]: ");
cont = u.next().charAt(0);
if (cont == 'Y') {
System.out.print("Enter another number: ");
another = u.nextDouble();
another = another;
} else {
System.out.println("End of Program");
}
} while (cont == 'Y');
}
}
You could put the value of the last value outside of the loop. Here's some pseudo-code to demonstrate what I mean:
variableStore = 0
loop:
perform operations
when printing out results to the user, assign variableStore = result
Next time, variableStore would be the value of the previous result
You don't need all those variables. Variable one always stores the latest result. Also, since your class only contains a single method, namely main, there is no need to declare class member variables. Refer to section 6.3 of the Java Language specification that explains about the scope of variables. The link is for Java 7 but is valid for all java versions.
Here is my rewrite of class practice. Note that I changed the class name to Practice, in keeping with Java naming conventions.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
char choose, cont = 'Y';
Scanner u = new Scanner(System.in);
System.out.print("Enter number 1: ");
double one = Double.parseDouble(u.nextLine());
double two = 0;
boolean invalidSelection = false;
do {
if (!invalidSelection) {
System.out.print("Enter another number: ");
two = Double.parseDouble(u.nextLine());
}
invalidSelection = false;
System.out.print(
"\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose = u.nextLine().charAt(0);
if ((choose == 'A') || (choose == 'a')) {
one += two;
System.out.println("The sum is " + one);
}
else if (choose == 'B' || choose == 'b') {
one -= two;
System.out.println("The difference is " + one);
}
else if (choose == 'C' || choose == 'c') {
one *= two;
System.out.println("The product is " + one);
}
else if (choose == 'D' || choose == 'd') {
one /= two;
System.out.println("The quotient is " + one);
}
else {
System.out.println("Invalid Selection");
invalidSelection = true;
continue;
}
System.out.print("Continue?[Y/N]: ");
cont = u.nextLine().charAt(0);
} while (cont == 'Y' || cont == 'y');
System.out.println("End of Program");
}
}
Note, in the above code, that I replaced calls to method next (of class java.util.Scanner) with calls to method nextLine. Refer to this SO question for more details.
Scanner is skipping nextLine() after using next() or nextFoo()?
I recommend that you run the code with a debugger in order to understand how it works.
Here is the output from a sample run.
Enter number 1: 3
Enter another number: 2
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: x
Invalid Selection
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: c
The product is 6.0
Continue?[Y/N]: y
Enter another number: 4
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: b
The difference is 2.0
Continue?[Y/N]: y
Enter another number: 0.5
Select an operation
[A]Addition
[B]Subtraction
[C]Multiplication
[D]Division
Choose: d
The quotient is 4.0
Continue?[Y/N]: n
End of Program
Try this code(it works for me):
import java.util.Scanner;
public class practice {
static double prevAns = 0;
static double another;
static double one;
static double add,sub,mul,div;
static boolean contin = false;
public static void main (String []args){
while(true){
char choose,cont;
Scanner u=new Scanner(System.in);
if (!contin){
System.out.print("Enter number 1: ");
one= Double.parseDouble(u.nextLine());
} else {
one = prevAns;
}
System.out.print("Enter number 2: ");
double two= Double.parseDouble(u.nextLine());
System.out.print("\nSelect an operation\n[A]Addition\n[B]Subtraction\n[C]Multiplication\n[D]Division");
System.out.print("\n\nChoose: ");
choose=u.next().charAt(0);
if((choose=='A')||(choose=='a')){
add = one+two;
prevAns = add;
System.out.println("The sum is "+add);}
else if (choose=='B'||choose=='b') {
sub=one-two;
prevAns = sub;
System.out.println("The difference is "+sub);
}else if (choose=='C'||choose=='c'){
mul=one*two;
prevAns = mul;
System.out.println("The product is "+mul);
}else if(choose=='D'||choose=='d'){
div=one/two;
prevAns = div;
System.out.println("The quotient is "+ div);}
else{
System.out.println("Invalid Selection");
}
System.out.print("Continue?[Y/N]: ");
cont=u.next().charAt(0);
if(cont=='Y'){
contin = true;
} else{
System.out.println("End of Program");
}
}
}
}

Calcu: How to add the operator before each number like a real calc

I'm just trying to build a calculator and I have no idea how to prompt an operator before each number. I'm trying to build a calculator and have as many number inputs as specified but they can cancel out of it by pressing -1 and it will still return the final value.
But i tried using a string statements but I'm new to coding and don't know where to start.
int operator;
int howmany;
int i=0;
int all = 0;
double div;
int scan;
System.out.println("Press 1 for addition, 2 for subtraction, 3 for \n
multiplication 4 for division or 5 for modules");
operator=scanner.nextInt();
if(operator < 1 || operator >5) {System.out.println("Restart
calculator");System.exit(0);}
System.out.println("How many numbers will you be using?");
howmany = scanner.nextInt() -1 ;
if (operator == 1){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all += scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 2){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all -= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 3){
all = 1;
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all *= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 4){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all = scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 5){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all %= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
}
}
When you don't know where to start when coding, it can help to write the algorithm in sentences first, and then convert into code. For a calculator program for example, I would start with this basic structure:
// need a data structure to hold all numbers
// need a data structure to hold all operations
while(the user wishes to continue) {
while(the user has not hit =) {
// use the scanner to get the next number (if it's -1, exit program)
// use the scanner to get the next operator (if it's = then exit inner
// loop to report result)
}
// need variable to hold calculation result, instantiate to first number
for(loop through numbers data structure) {
// apply next operator to the running result and next number
}
// report result to user
}
Something else to consider: a calculator should be able to use -1 in calculations. I'm not sure if this is a requirement of what you're working on, so I left it as you described, but what would be more in line with the spirit of a calculator would be to do something like ask the user after each successful calculation if they'd like to continue (y/n).

Random two-digit number guessing game in Java

I'm working on a "game" for the user to guess a random two-digit number, and this is my "robust" version so far:
import static java.lang.System.*;
import java.util.*;
public class RandomNumberGuessing {
public static Scanner scan = new Scanner(in);
public static void main(String args[]){
Random generator = new Random ();
int Low = 10;
int High = 99;
int answer = generator.nextInt (High - Low) + Low;
int answerFirstDigit = Integer.parseInt(String.valueOf(answer).substring(0,1));
int answerSecondDigit = Integer.parseInt(String.valueOf(answer).substring(1,2));
int count = 0;
out.println ("Welcome to the two digit number guessing game!");
out.println ("We have randomly chosen a two-digit number");
out.println ("And you have to guess it after 5 tries!");
out.println ("Guess the number: ");
while (!scan.hasNextInt ()) {
scan.next ();
out.println ("You have to input a valid two-digit integer!");
}
int guess = scan.nextInt ();
while (guess != answer && count < 4){
count ++;
out.println("Wrong number! You have " + (5 - count) + " tries left:");
if (Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerFirstDigit){
out.println("But you got the first digit correctly!");
} else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit){
out.println("But you got the second digit correctly!");
} else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit || Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerSecondDigit){
out.println("One or two digits are correct but in the wrong place!");
}
while (!scan.hasNextInt ()) {
scan.next ();
out.println ("You have to input a valid two-digit integer!");
}
guess = scan.nextInt ();
}
if (guess == answer){
out.println("Congratulations! The number was " + answer + "!");
} else{
out.println("The number was " + answer + ". Better luck next time!");
}
}
}
But I'm having a problem with forcing the user to input a two-digit number only. I tried using:
while(guess < 10 || guess > 99){
scan.next();
out.println("Invalid number!");
guess = scan.nextInt();
}
I added that after the while loop to make sure the user entered an integer, and when I enter a 3 or 4-digit number in the console (I run the code on IntelliJ IDEA), it just seems to hang with no response. It doesn't even print out "Invalid number!" and just hangs. Do I have to rewrite the code using methods or are there any other things I can add to the existing code to make sure the user enters a TWO-DIGIT INTEGER? Thanks in advance
To check that the user enters just two digit numbers, i would use two methods to verify that.
Things to check:
User must enter something, i.e do not accept null or empty
Everything user enters must be exactly two characters long
When the characters are two, they have to all be digits
In your program you can do these
1. Get input as string
2. Call validString
3. If valid, then convert to integer
4. Check that number is between range (if the user entered 01, this evaluates to true). Integer.ParseInt could catch this but good to check anyway
Complete program should be something like this
import static java.lang.System.*;
import java.util.*;
public class RandomNumberGuessing {
public static Scanner scan = new Scanner(in);
public static void main(String args[]) {
final int tries = 5; // max number of tries
Random generator = new Random();
int Low = 10;
int High = 99;
int answer = generator.nextInt(High - Low) + Low;
int firstDigit = getFirst(answer);
int secondDigit = getSecond(answer);
out.println("Welcome to the two digit number guessing game!");
out.println("We have randomly chosen a two-digit number");
out.println("And you have to guess it after " + tries + " tries!");
int guess = 0; // number guessed
int count = 0; // number of failed guesses
do {
out.println("Guess the number: ");
String guessString = scan.nextLine(); // just read everything
// entered
if (validString(guessString)) {
guess = Integer.parseInt(guessString);
if (guess >= Low && guess <= High) { // check range and only
// process valid range
count++;
if (count == tries) {
out.print("Max guess reached.\nThe values were ");
out.println(firstDigit + " and " + secondDigit);
break;
}
out.println("You guessed " + guess);
// get the first and second digits
int first = getFirst(guess);
int second = getSecond(guess);
// compare them and process
if (guess == answer) {
out.println("Congratulations. You made the right guess after "
+ count + " tries");
} else if (first == firstDigit) {
out.println("Guessed the first number rightly");
} else if (second == secondDigit) {
out.println("Guessed the second number rightly");
} else {
out.print("No matching guess. You have ");
out.println((tries - count) + " guesses left");
}
} else {
out.println("Out of range!");
}
} else {
out.println("Bad Value.");
}
} while (guess != answer && count < tries);
}
// Validate an input Checks for length [2 characters] and that everything is
// a digit
private static boolean validString(final String guess) {
if (guess != null && !guess.isEmpty()) { // if not null and not empty
if (guess.length() == 2 && isAllDigits(guess)) { // length and digit
return true;
} else {
return false;
}
} else {
return false;
}
}
// Verify that all characters in a string are numbers
private static boolean isAllDigits(final String input) {
for (char c : input.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
// get the first digit
private static int getFirst(final int value) {
return Integer.parseInt(String.valueOf(value).substring(0, 1));
}
// Get the second digit
private static int getSecond(final int value) {
return Integer.parseInt(String.valueOf(value).substring(0, 1));
}
}

Simple guessing game. "Your first guess is...."

I am creating this simple guessing game with three tries, but I need help adding code so it can display "First guess" followed by the integer the user puts in, "Second guess", etc... I currently just have "Enter your guess" which is the first try. What do I need to do? I'm confused on how to go about doing this. Sorry if the question is confusing.
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
int attempts = 0;
do {
attempts++;
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess < 1 || guess > 10) {
System.out.println("out of range");
attempts = +1;
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN && attempts < 3);
if (guess != randomN && attempts == 3) {
System.out.println("Number is " + randomN);
}
}
}
You could create another static method outside main, where you can output a custom message depending on the attempts.
public static String describe(int attempts) {
switch(attempts) {
case 1: return "First guess: ";
case 2: return "Second guess: ";
case 3: return "Third guess: ";
default: return "Enter your guess: "; //should not happen
}
}
Then in your main use it like so:
...
do {
attempts++;
System.out.print(describe(attempts));
...
}

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;
}
}
}
}

Categories

Resources