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();
Related
Am trying to write simple program to find average of 3 int values, but it always seems to get the average wrong
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num1 + num3)/3));
}
}
Help is greatly appreciate
Besides having num1 twice and missing num2, as already mentioned above, you will always get integer-results only, e.g. for num1 = 1, num2 = 2 and num3 = 2 your code will plot 1 as result instead of 1.667. You might enforce double-results in your output by writing
System.out.println("The average is:"+ ((num1 + num2 + num3) / 3.0));
It's supposed to be:
import java.util.Scanner;
public class IntegerAverage {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num1;
int num2;
int num3;
// Ask user
System.out.println("Input 1st number");
num1 = in.nextInt();
System.out.println("Input 2nd number");
num2 = in.nextInt();
System.out.println("Input 3rd number");
num3 = in.nextInt();
// Print answer
System.out.println("The average is:"+ ((num1 + num2 + num3)/3));
}
}
You accidentally added num1 twice, and forgot num2.
How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again
import java.util.Scanner;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int years;
int minutes;
System.out.println("Years to Minutes Converter");
System.out.print("Insert number of years: ");
years = reader.nextInt();
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
Use Scanner.hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Example code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt())
sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt())
sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since hasNextXXX methods doesn't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.
Ok I made this:
package reader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
int years;
int minutes;
String data = null;
System.out.println("Years to Minutes Converter");
boolean test = false;
while (test == false) {
System.out.print("Insert number of years: ");
String regex = "\\d+";
data = reader.next();
test = data.matches(regex);
if (test == false) {
System.out.println("There is a problem try again");
}
}
years = Integer.valueOf(data);
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
It will say:
Years to Minutes Converter
Insert number of years: dsds
There is a problem try again
Insert number of years: ..
There is a problem try again
Insert number of years: 2
That is 1051200 in minutes.
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
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.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Sorry for the noob question. This is my first day trying out Java programming. I need help retrieving the users input of which operator the user wants to use with integers.
import java.util.Scanner;
public class calculator {
public static void main (String args[]) {
Scanner number = new Scanner(System.in);
double num1,num2,answer;
char operator;
System.out.println("Enter first number: ");
num1 = number.nextDouble();
operator = number.nextChar(); /* the "nextChar" is not correct */
System.out.println("Enter second number: ");
num2 = number.nextDouble();
if (operator = '+'){
answer = num1 + num2; /* If statements do not work like this */
} /* I would use "else if", unsure if it allows */
if (operator = '-'){
answer = num1 - num2;
}
if (operator = '*'){
answer = num1 - num2;
}
if (operator = '/'){
answer = num1 / num2;
}
System.out.println(num1 + num2 + operator + answer);
}
}
Edited Version:
import java.util.Scanner;
public class calculator{
public static void main (String args[]) {
Scanner userInput = new Scanner(System.in);
String operator;
double num1,num2,answer = 0;
System.out.println("Enter first number: ");
num1 = userInput.nextDouble();
System.out.println("Enter operator: ");
operator = userInput.next();
System.out.println("Enter second number: ");
num2 = userInput.nextDouble();
if (operator.equals ("+")){
answer = num1 + num2;
}
else if (operator.equals ("-")){
answer = num1 - num2;
}
else if (operator.equals ("*")){
answer = num1 * num2;
}
else if (operator.equals ("/")){
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
First number:10.0
Operator:*
Second number:3.14
Answer: 31.400000000000002
Thanks a lot guys! Helped a lot!
Ok. This works and can help you on your road to java
public class Tester4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double num1, num2, answer = 0;
String operator;
System.out.println("Enter first number: ");
num1 = input.nextDouble();
System.out.println("Enter operator: ");
operator = input.next();
System.out.println("Enter second number: ");
num2 = input.nextDouble();
if(operator.equals("+")) {
answer = num1 + num2;
} else if(operator.equals("-")) {
answer = num1 - num2;
} else if(operator.equals("*")) {
answer = num1 - num2;
} else if(operator.equals("/")) {
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
Use == in comparisons, not = (that means assignation).
As other have already pointed out, use the == operator to check for equality. The = operator will assign values instead.
In order to read a single character from the Scanner, take a look at the following question: Scanner method to get a char. There you'll find the suggestion to use Scanner.findInLine() method, which receives a regular expression as an argument. Providing the . wildcard character as pattern, you'll be able to get a String with the one next character, and using charAt(0) on it, you'll get it as a char.
Scanner sc = new Scanner("abc");
char ch = sc.findInLine(".").charAt(0);
System.out.println(ch); // prints "a"
Of course, you could also just use Scanner.next() to get the next word as a String, and just get its first character. But take into account that doing so would discard from the input buffer the rest of the word.
You need to use
if (operator == '+')
Notice the 'double equal to'.