Simple Calculator Gone Wrong in java [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
I'm trying to teach my friend Java. I tried this simple calculator.
public static void main(String[] args) {
boolean powerOn = true;
while(powerOn) {
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to the calculator\nPlease enter a number (Enter 3.14 for PI)");
double firstNumber = userInput.nextDouble();
if(firstNumber == 3.14) firstNumber = Math.PI;
System.out.println("Please enter an operation(+,-,*,/, Square Root)");
String operation = userInput.next();
if(operation.equalsIgnoreCase("Square Root")) System.out.println(Math.sqrt(firstNumber));
else {
System.out.println("Please enter another number");
double secondNumber = userInput.nextDouble();
if(secondNumber == 3.14) secondNumber = Math.PI;
if (operation.equals("+")) {
if(firstNumber == 9 && secondNumber == 10) System.out.println("21");
else System.out.println(firstNumber+secondNumber);
}
else if (operation.equals("-")) System.out.println(firstNumber-secondNumber);
else if (operation.equals("*")) System.out.println(firstNumber*secondNumber);
else if (operation.equals("/")) System.out.println(firstNumber/secondNumber);
}
System.out.println("Power off?");
String off = userInput.next();
if(off.contains("y")) System.exit(1);
}
}
If you do square root, it prints enter another number and then throws an exception... I know what's happening, but why and how do I prevent it?
And just a side note can someone explain to me the difference between Scanner#next() and Scanner#nextLine?

next() returns the string before the space while nextLine() as you might have guessed returns the whole line .
You are probably also getting the error because of the same reason as your string "Square Root" has a space and hence operation variable always have "Sqaure" value assigned to it rather than "Square Root".
This pushes it to the else block instead of if.

To fix your issue add a scan.nextLine();
Before you scan in the operation. And while scanning in the operation use a scan.nextLine(); as well instead of the scan.next();
Think of the scan as the location of the cursor. A scan.nextDouble(); will place the cursor after the last digit of the number, and a scan.nextLine(); will scan in what ever is inbetween the cursor's location and the beginning of the next line. scan.next(); won't scan in the entire line.

You need to update the following code
String operation = userInput.next();
with following
String operation = userInput.nextLine();
The reason being the next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
In your current code, when you try to get the square root, the operation will just store "Square" instead of "Square Root" and therefore the following if condition isn't satisfied
if(operation.equalsIgnoreCase("Square Root"))
and the code goes into else condition and asks for another number and tries to process it and in the else block it throws error on this line
double secondNumber = userInput.nextDouble();
Apart from changing the next() to nextLine() in your code, you need to update following
double firstNumber = userInput.nextDouble();
with
double firstNumber = userInput.nextDouble();
userInput.nextLine();
to ensure that the scanner doesn't skip your nextLine() because in nextDouble() method only the double is consumed and the next line characters (\n) aren't.
Similarly update
double secondNumber = userInput.nextDouble();
with
double secondNumber = userInput.nextDouble();
userInput.nextLine();
For more info about skipping of nextLine() method while using nextDouble() refer this link.

Related

How do I prevent an error message from repeating in Java?

I'm trying to write a program to calculate factorial but I can't figure out why the Error message displays twice if I enter a letter instead of an integer.
I feel like the issue has to do with Line 29 c = sc.next().charAt(0);, but am not sure how to fix it. Any help is appreciated.
My program:
public class Factorials {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = 'Y';
int num = 0;
do
{
System.out.print("Enter a number to calculate its factorial: ");
while (!sc.hasNextInt()) {
System.out.println("Invalid Entry - Enter only Integers! Try Again: ");
sc.nextLine();
}
int result = 1;
num = sc.nextInt();
for(int i = 1; i <= num; i++) {
result = result * i;
}
System.out.println("The factorial of " + num + " is: " + result);
System.out.println("Do you wish to continue? Y/N: ");
c = sc.next().charAt(0);
}while(c == 'y' || c == 'Y');
sc.close();
}
}
Simple fix: Change the sc.nextLine(); in your code to a sc.next() and you should be good to go. This error occurs because .nextLine() considers the enter/return key as a separate character, while .next() doesn't. (The enter key when you press it after entering either 'y' or 'n': if you try it, the error message doesn't print twice if you enter a letter the first time you run the program).
Side note: You probably want it to be a .print(/*invalid input sentence*/) instead of a .println() to go along with how you take in your other number values.
Otherwise, you're good!
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern
As jdk doc shows, the 'sc.next' method will return when it reaches space, enter or return. So when you enter 'y' with enter, the enter character is still in buffer. You can assign sc.nextLine to a variable, like
String str = sc.nextLine();
System.out.println(str);
You can see the enter character and your input character.
Both #TheSj and #Lahiru Danushka answer could solve this problem.
add sc.nextLine(); after c = sc.next().charAt(0);

Only allow double inputs with java scanner

import java.util.Scanner;
import java.io.*;
public class Positive {
public static void main (String args[]) {
double first;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter first value" + "\n");
first= scan.nextDouble();
if (first>0.00) {
System.out.println("Please enter second value");
}
else if (first <0.00) {
first =-first;
System.out.println(first);
System.out.println("Please enter second value");
}
double second;
Scanner scaning = new Scanner(System.in);
second = scan.nextDouble();
if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}
}
}
Task:
If the value is positive, request a second value. Print the difference between these two numbers so that the difference is always positive. For instance, if the first value is 10.3 and the second is 4.1, you would print the result of 6.2. If the first value is 3.8 and the second is 13.4 you would print the result 9.6.
If the first value read is negative, print its positive equivalent. For instance, if its value is –89.6 you should print 89.6.
If the first value is not a number, give appropriate error message (The standard error message from Java (e.g. “Exception in thread "main” ...”) does not count! Have a look at the Java API or Stack Overflow how to approach this).
The rest of the code runs correctly but I don't know how to only include double values in the input
By using Scanner::nextDouble you are forcing the input to only be doubles, but if you were to use Scanner::nextLine then you could then try to convert to a double and if that fails then print the message
Scanner scan = new Scanner(System.in);
System.out.println("Enter double");
String line = scan.nextLine();
double firstNum = 0.00;
try {
firstNum = Double.parseDouble(line);
}
catch (NumberFormatException e) {
System.err.println("Not a double");
}
Also, rather than doing
if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}
it would be easier to do
System.out.println (Math.abs(first - second));
and also you should remove this line as it is not necessary and you are not even using it
Scanner scaning = new Scanner(System.in);

IF statement isn't checking variable

Hello I'm trying to write a program that prints 3 numbers from a range being restricted to numbers from 0 to 99,but my If statement isn't double checking the variable.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0);
System.out.println("Outside range program terminated.");
Two problems that I see:
Your second input (within the first IF) is not checked with the code shown.
The else statement will NOT check the above mentioned problem because you've already passed that decision point when the original IF executed. The else is dependent on the IF's result. Here would be one way to fix.
Finally the 'else' needs brackets { }.
int input1 = 0;
Boolean myLoop = true; //Sets up our loop flag
while(myLoop){ //Loop while true
System.out.println("Please enter an integer between 0-99");
input1 = Input.nextInt();
if (input1>99||input1<0){ //If input is outside the range send msg.
System.out.println("Data range error");
}else{ //If input is in range, end loop.
myLoop=false;
}
}
This will continue to check until it get valid values.
While the others have given you a good code sample, I will like to point out where your code issue is. The code is not doing the double checking here because you have placed a semi-colon right at the end of the second if-else check, and the program will do nothing when it fulfill the if condition.I have replaced it with curly bracket. Try to compile and run it again.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0){
System.out.println("Outside range program terminated.");
}

How to verify that input is a positive integer in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create an input that will Verify the input is an Integer, and that it is positive. Right now i have this. How should i check if the integer is positive
EDIT: Also i need it to keep asking until you enter a positive integer
/**
* pre: none
* post: returns a positive integer as entered by the user
*/
public static int getInput(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
while (!scan.hasNextInt()){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
scan.next();
}
a = scan.nextInt(); //Assigns entered integer to a
return a; //replace with correct code
}
You can do this in a single loop, similar to the one that you have for skipping invalid input. However, since the loop needs to ensure two things (i.e. a number is entered, and that number is positive) you need to modify its body.
Since the input needs to be done at least once, a do/while loop is a better choice.
Start with a loop that satisfies the condition that you want, i.e. "I got a number, and that number is positive":
int num = -1;
do {
// We'll provide content of this in a moment
} while (num <= 0);
Once the loop exits, you know that num > 0, so the only task now is to write a body of the loop that takes us closer to that goal.
Inside the loop we need to check that the user entered a number. If he did, we harvest that number; otherwise, we tell the user to try again:
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scan.nextLine();
}
That's it - now you have a loop body that reads the value for you, and a loop condition that ensures that the value is positive on exit. Combine the loop with the loop body, and try it out. It should do the trick.
Simple:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
On a side note:
Check Math.signum()
Returns the signum function of the argument; zero if the argument is
zero, 1.0 if the argument is greater than zero, -1.0 if the argument
is less than zero.
You can try this:
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}

My program is terminated without scanning string [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
When I execute my code my program is terminated without scanning the string.
double x, y;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Number: ");
x = scan.nextDouble();
System.out.println("Enter Number 2: ");
y = scan.nextDouble();
System.out.println("Enter Operater: x,+,/,-");
s = scan.nextLine();
if(s.equals("x"))
{
System.out.print(x * y);
}
else if(s.equals("+"))
{
System.out.print(x + y);
}
else if(s.equals("/"))
{
System.out.print(x / y);
}
else if(s.equals("-"))
{
System.out.print(x - y);
}
scan.close();
my program ends before s = scan.nextline();
How come it ends before?
End of line you leave in the buffer.
next( ) reads a token from the buffer until the next white space, while nextLine( ) reads up to \n
...
System.out.print("Enter Number 2: ");
y = scan.nextDouble();
System.out.print("Enter Operater: x,+,/,-");
s = scan.next();
...
Enter Number: 1
Enter Number 2: 2
Enter Operater: x,+,/,--
-1.0
The user input, optimally, would look like this:
-CURSOR HERE- num1 NEWLINE
num2 NEWLINE
operator NEWLINE
If you do several nextDouble() calls, the program will read one double first.
num1 -CURSOR HERE- NEWLINE
num2 NEWLINE
operator NEWLINE
Then, the user must type an enter to submit the input, so the second nextDouble() can't find anything to read, since there is no number directly after the cursor. It needs a nextLine() to absorb the newline.
Unfortunately, you have a nextLine() in the wrong place, which absorbs the newline.
num1 NEWLINE
-CURSOR HERE- num2 NEWLINE
operator NEWLINE
So, your program absorbs the double in the first nextDouble(), nothing in the second, and the newline in nextLine().
To fix this, put a scan.nextLine() right after each nextDouble(). You don't have to read the nextLine() calls into anything, other than the one that has the operator.

Categories

Resources