Below is the code I have so far, it is a calculator for my computer science class. The problem I am having is that on the second run of the program the System.out.print("Would you like to perform a calculation? (y/n) "); runs twice instead of once. I have already turned in the project, but I would like to know why it does this and how, in my future programs, I can fix it. I'll post the rest of the code below.
I appreciate all of your help, I credit the "A" that I got on it to all of you. Thanks!
/**
* A calculator with multiple functions.
* #author ()
* #version (version 2.1)
*/
import java.io.*;
import java.util.Scanner;
public class Calc
{
public static void main(String args[])
{
Scanner reader = new Scanner(System.in);
String cont = "", funct = "";
double fnum = 0, snum = 0, answer = 0;
while(true)
{
System.out.print("Would you like to perform a calculation? (y/n) ");
cont = reader.nextLine();
if (cont.equalsIgnoreCase("y"))
{
System.out.println("What function would you like to do?");
System.out.println("+?");
System.out.println("-?");
System.out.println("*?");
System.out.println("/?");
funct = reader.nextLine();
if (funct.equals("+"))
{
System.out.println("Simple addition calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum + snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("*"))
{
System.out.println("Simple multiplication calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum * snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
}
else if (cont.equalsIgnoreCase("n"))
{
break;
}
}
}
}
In all of your function conditions inside the loop, you are using reader.nextDouble(). This will only read the number (e.g "8") input not the new line (the enter) which is entered by the user after the number.
Following code for the minus(-) function will not print "Would you like to perform a calculation? (y/n) " twice as the new line is already read. Here reader.nextLine() is used instead of reader.nextDouble(). reader.nextLine() will read the whole line not only the number.
if (funct.equals("-"))
{
System.out.println("Simple subtraction calculator");
System.out.println("Enter first num: ");
fnum = Double.parseDouble( reader.nextLine());
System.out.println("Enter second num: ");
snum = Double.parseDouble( reader.nextLine());
answer = fnum - snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
You need to consume the newline character after you call nextDouble() and before the next nextLine() to prevent nextLine() consume the newline character. Otherwise funct = reader.nextLine(); will take the new line character as input and not wait for any more user input, which results in the repeat.
if (funct.equals("/"))
{
System.out.println("Simple division calculator");
System.out.println("Enter first num: ");
fnum = reader.nextDouble();
System.out.println("Enter second num: ");
snum = reader.nextDouble(); // consume the new line character
reader.nextLine();
answer = fnum / snum;
System.out.println("Answer: " + answer);
System.out.println(" ");
}
Try adding this reader.nextLine(); before the while loop ends, as mentioned below. This will clear the screen buffer.
else if (cont.equalsIgnoreCase("n"))
{
break;
}
reader.nextLine();
}
Hope this helps,
Basically what is happening is when you are using the reader.nextLine() method, there is still a newline character left in the buffer, which is picked up when calling nextLine(). So it's making an extra run with the newline character. If you run your program with newline as the input even for the first time, it will loop without doing anything. So, you just need to clear out the buffer before going into your while loop.
Related
When the user selects yes, it loops and starts again. When the user selects N, it should end the program but I am not sure what I am missing here. This is a program to tell you the x and y values when giving the slope and y-intercept to the program.
Java file
int slope;
int yintercept;
String newEquation;
boolean play = true;
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
while (play)
{
if (newEquation.equals("Y"))
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
if (newEquation.equals("N")){
play =false;
}
else{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
}
}
}
Why do you have the same code in if (newEquation.equals("Y")) and else part? If you expect user only to enter "Y" or "N", then you can put else in fron, like this:
else if(newEquation.equals("N"))
and delete else part.
Because the way how you wrote it, it tests if input is "Y", and then second time in the same loop iteration it is going to test if input is "N", so that means that your program take the slope info twice once when it goes trough loop, because else refers only to "N".
Try a do-while construct, as well as a equalsIgnoreCase (to make "y" and "Y" both tested against "Y").
int slope;
int yintercept;
String newEquation;
boolean play = true;
do
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
} while newEquation.equalsIgnoreCase("Y")
(I have only cut-and-pasted your lines, but have not compiled and tested. My apologies if I missed something.)
The do-while tests if the user has typed a Y/y after the first round. Note that the user doesn't have to type N/n, but instead could type, say, q in order for the loop to terminate.
I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0
When i run it, nothing happens. Whats weird to me is how the systemoutprintln asking what you want to do doesnt work either. The scanner is called earlier in it by the way. If im doing something completely wrong please tell me :) Any help would be tremendous.
Scanner scanner3 = new Scanner(System.in);
String operator = scanner3.nextLine();
System.out.println("What do you want to do? (add, subtract, multiply, or divide?)");
switch (operator){
case "add": System.out.println("Enter number one ");
Scanner scanner4 = new Scanner(System.in);
double addnum1 = scanner4.nextDouble();
System.out.println("Enter number two ");
Scanner scanner5 = new Scanner(System.in);
double addnum2 = scanner5.nextDouble();
System.out.print("the answer is: ");
System.out.println( addnum1 + addnum2);
break;
case "subtract": System.out.println("Enter number one");
Scanner scanner7 = new Scanner(System.in);
double subnum1 = scanner7.nextDouble();
System.out.println("Enter number two ");
Scanner scanner8 = new Scanner(System.in);
double subnum2 = scanner8.nextDouble();
System.out.print("the answer is: ");
System.out.println( subnum1 - subnum2 );
break;
case "multiply": System.out.println("Enter number one");
Scanner scanner9 = new Scanner(System.in);
double mulnum1 = scanner9.nextDouble();
System.out.println("Enter number two ");
Scanner scanner10 = new Scanner(System.in);
double mulnum2 = scanner10.nextDouble();
System.out.print("the answer is: ");
System.out.println( mulnum1 * mulnum2 );
break;
case "divide": System.out.println("Enter number one");
Scanner scanner11 = new Scanner(System.in);
double divnum1 = scanner11.nextDouble();
System.out.println("Enter number two ");
Scanner scanner12 = new Scanner(System.in);
double divnum2 = scanner12.nextDouble();
System.out.print("the answer is: ");
System.out.println( divnum1 / divnum2 );
break;
}
the first printing
System.out.println("What do you want to do? (add, subtract, multiply or divide?)");
was after the
.nextLine()
so your program expects the input before printing the first message.
you can use same scanner for all cases, much better and cleaner code.
Scanner scanner_all = new Scanner(System.in);
System.out.println("What do you want to do? (add, subtract, multiply or divide?)");
String operator = scanner_all.nextLine();
switch (operator){
case "add":
System.out.println("Enter number one ");
double addnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double addnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( addnum1 + addnum2);
break;
case "subtract":
System.out.println("Enter number one");
double subnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double subnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( subnum1 - subnum2 );
break;
case "multiply":
System.out.println("Enter number one");
double mulnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double mulnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( mulnum1 * mulnum2 );
break;
case "divide":
System.out.println("Enter number one");
double divnum1 = scanner_all.nextDouble();
System.out.println("Enter number two ");
double divnum2 = scanner_all.nextDouble();
System.out.print("the answer is: ");
System.out.println( divnum1 / divnum2 );
break;
}
I want it to loop again when the user enters "Y" or "y" and quit when they enter "N" or "n". The quitting option works, however, when they enter Y/y, it shows the first system out, but does not let the user pick which operation they wish to do. Instead the option to continue pops up again and inhibits the user from making any choice.
Here is the code:
import java.util.Scanner;
public class Calc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numOne, numTwo, ans;
String option;
do {
System.out.println(
"For addition press '1', for subtraction press '2', for division press '3', for multiplication press '4'");
String choice = input.nextLine();
if (choice.contains("1")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne + numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
else if (choice.contains("2")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne - numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("4")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne * numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("3")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne / numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
System.out.println("Press 'Y' to continue or 'N' to quit.");
option = input.next();
} while (option.equals("Y") || option.equals("y"));
if (option.equals("N") || option.equals("n")) {
System.out.println("Thank you. ");
}
}
}
If anyone can help me, it'd be greatly appreciated. Thanks!
Please change below line in your code
String choice = input.nextLine();
from this code
String choice = input.next();
There trouble you see here is the use of nextLine after nextDouble. Check here [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Your problem appears to be at the beginning of your do-while loop as such:
System.out.println(
"For addition press '1', for subtraction press '2', " +
"for division press '3', for multiplication press '4'");
String choice = input.nextLine();
This is the only place where you use nextLine method (rahter than next or nextDouble and so on). This means that after you've read the option argument at the end of the iteration:
option = input.next();
there's still a new line character that hasn't been read by the scanner. When you do nextLine() in the next iteration it reads the new line character before the user has any chance to input something).
Either change that first line to input.next() as well, or make sure every time you read a value, you clear the new line character (for instance by reading nextLine and then casting the value - this would also allow you to do input validations).
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am trying to make a simple calculator which can add, substract, divide and multiply any two numbers.
The way it works is that I ask for a number, then I ask for a sign (+,-,*,/) , and then I ask for the second number. The math should be done accordingly afterwards.
However I can't get the 'math sign' to be recognized properly by the program.
Here is my code:
package practice1;
import java.util.Scanner;
public class maiin {
public static void main(String[] args){
System.out.println("it works.");
double num1;
double num2;
String sign;
double total;
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
num1 = input.nextDouble();
System.out.println("Enter a +,-,/,* sign: ");
sign = input.nextLine();
input.nextLine();
System.out.println("Enter another number: ");
num2 = input.nextDouble();
if (sign.equals("+")){
total = num1 + num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("-")) {
total = num1 - num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("/")) {
total = num1 / num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("*")) {
total = num1 * num2;
System.out.println("Your total is: " + total);
} else {
System.out.println("Please enter the a proper sign");
}
When I run the program, I always get "Please enter the a proper sign".
Thank you in advanced.
I think you need to change
sign = input.nextLine();
input.nextLine();
to
sign = input.nextLine();
sign.nextLine();