String sentinel on integer input Java - 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;
}
}
}
}

Related

Another way except of UserInput

I would like to know how to do this with another way except of userinput? I don't want to write the values I want to do this the user
Calculate calculation = new Calculate();
int sum = calculation.sum(2, 5);
int testSum = 7;
#Test
public void testSum() {
System.out.println("#Test sum(): " + sum + " = " + testSum);
assertEquals(sum, testSum);
}
}
I guess the following might help:
public void test() {
int number1 = 0;
int number2 = 0;
int expected = 0;
System.out.println("Enter first number");
int state = 0;
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("E")) {
input = scanner.nextLine();
input = input.toUpperCase();
if (!input.equals("") && Character.isDigit(input.charAt(0))){
switch(state) {
case 0:
number1 = Integer.parseInt(input);
System.out.println("Enter second number");
break;
case 1:
number2 = Integer.parseInt(input);
System.out.println("Enter expected result");
break;
case 2:
expected = Integer.parseInt(input);
System.out.println("Result: " + (number1 + number2) +
" | Expected: " + expected + System.lineSeparator());
System.out.println("Enter first number");
state = -1;
break;
default:
break;
}
state++;
}
}
scanner.close();
System.out.println("Exiting");
}

Scanner skipping nextLine(); after do while loop

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}

How to prevent string from printing repeatedly in while loop?

I'm currently working on some exercises given to me by my teacher. These are for the holidays so I won't be able to ask for help there.
I have this piece of code which creates a multiplication table from an integer defined by the user, ranging from a minimum and maximum also defined by the user.
Before setting any of my variables to the next integer in my Scanner, I do a check to see if the Scanner actually has an integer. This works fine but I don't want it to print out the error message a billion times.
Any tips/tricks or other special ways of getting around this?
public class MultiplicationTable
{
private int intervalMin;
private int intervalMax;
private int multiplier;
private int result;
private Scanner sc;
public MultiplicationTable()
{
multiplier = 0;
intervalMin = 0;
sc = new Scanner(System.in);
while (multiplier == 0)
{
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt())
{
multiplier = sc.nextInt();
}
else
{
System.out.println("Input is not an integer\n");
}
}
while (intervalMin == 0)
{
System.out.println("\nPlease enter the integer defining the start of the table");
if (sc.hasNextInt())
{
intervalMin = sc.nextInt();
}
else
{
System.out.println("Input is 0 or not an integer\n");
}
}
while (intervalMax == 0)
{
System.out.println("\nPlease enter the integer defining the end of the table");
if (sc.hasNextInt())
{
int i = sc.nextInt();
if (i > intervalMin)
{
intervalMax = i;
}
else
{
System.out.println("\nEnd integer must be greater than start integer");
}
}
else
{
System.out.println("Input is 0 or not an integer");
}
}
System.out.println("\nTable for integer " + multiplier + " from " + intervalMin + " to " + intervalMax + "\n");
for (int i = intervalMin; i <= intervalMax; i++)
{
result = i * multiplier;
System.out.println(i + " * " + multiplier + " = " + result);
}
}
}
You didn't consume what user entered into the scanner buffer, that's why sc.hasNextInt() keeps getting executed without waiting for the next user input.
The solution is to add sc.nextLine() after the if condition.
For example:
boolean gotInteger = false;
while (!gotInteger) {
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt()) {
multiplier = sc.nextInt();
gotInteger = true;
} else {
System.out.println("Input is not an integer\n");
}
sc.nextLine();
}
Pleas try this, just wrap all your code inside try catch:
try {
while (intervalMax == 0) {
System . out . println("\nPlease enter the integer defining the end of the table");
if (sc . hasNextInt()) {
int i = sc . nextInt();
if (i > intervalMin) {
intervalMax = i;
} else {
throw new Exception("\nEnd integer must be greater than start integer");
}
}
}
} catch (Exception e) {
System . out . println(e . getMessage());
}

Very simple game about Guessing The Number

/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}

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