Continuous Calculator - java

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

Related

Suggestions to improve code about primes?

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

Simple calculator program in Java

I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}

How to keep requesting user to select a valid option?

So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
Your requirement can be done easily with do...while loop. Sample code is as follows:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
Hope this helps.
//put the menu logic
while(choice > 3 || choice < 1) {
//put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
import java.util.Scanner;
public class Furniture2Test
{
public static void main(String[] args)
{
wood();
} // end main
public static void wood()
{
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = read_range(keyboard, 1, 3);
if(choice == 1)
{
choice = pineCost;
}
else
if(choice == 2)
{
choice = oakCost;
}
else
if(choice == 3)
{
choice = mahoganyCost;
}
else
if(choice > 3 || choice < 1)
{
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice)
{
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = read_range(keyboard, 1, 2);
if(sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else
if(sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
private static int read_range (Scanner scanner, int low, int high) {
int value;
value = scanner.nextInt();
while (value < low || value > high) {
System.out.print("Please enter a value between " + low + " and " + high + ": ");
value = scanner.nextInt();
}
return value;
}
} // end class
whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//
the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)
if you want it to stop remove the wood() call
if you also want to clear the value for choice(instead of -1) you can assign it to null
choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.
When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).
Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).
You should be using a while-loop instead of recursive calls
You should never call size(choice) with anything other then a valid choice
Take a look at The while and do-while statement for more details

Need help making a random math generator

What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();

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