Without directly giving me the answer can someone help me with this simple calculator that I am trying to write?
Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console.
I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.
import java.util.Scanner;
public class simpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare my variables
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
//ask for user input
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform on these numbers?");
System.out.println("add " +"multiply " +"subtract " + "divide ");
userChoice = input.nextLine();
if (userChoice == "add"){
System.out.print("Answer = " + addition);
}
//calculator formulas
addition = firstNum + secondNum;
multiplication = firstNum * secondNum;
subtraction = firstNum - secondNum;
division = firstNum / secondNum;
}
}
nextInt() reads just the number and not the end of the line after the number. You will need a nextLine() after each nextInt() to consume the rest of the line.
Also, before you beat your head against the wall the following statement won't work for you:
if (userChoice == "add")
== tests for reference equality.
.equals() tests for value equality. So you need something like this instead:
if (userChoice.equals("add"))
I wanted to give you that freebie because I love your attitude that you don't want anyone to give you the answer. That is great that you wan to learn it. Keep up the good work.
Saying that String a == String b means that you're comparing two strings to see if they have reference equality, while saying a.equals(b) will compare the values stored in the string.
Reference equality is used to compare whether two object references point to the same object, which in this case you shouldn't be using as you're trying to compare whether the value of two variables are equal. So definitely go with
if(userChoice.equals("add"))
Related
I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
I am trying to create a program in which a user can enter 2 numbers and the program will take the 2 numbers and multiply them to get an answer. However, for this specific example, I am simply trying to take 2 numbers from a user and I want Java to add them. eg 1+1=2, instead of 1+1=11.
My code:
import javax.swing.JOptionPane;
public class MultiplicationTables {
public static void main(String args[]) {
//declare variables
String num1;
String num2;
int ans=0;
num1=JOptionPane.showInputDialog(null,"Enter a number");
num2=JOptionPane.showInputDialog(null,"Enter another number");
ans=Integer.parseInt(num1);
ans=Integer.parseInt(num2);
JOptionPane.showMessageDialog(null,"Your answer is " + (num1+num2));
}
}
num1 and num2 are String.
So as you write num1+num2 you get the result of their concatenation.
In fact, you don't use the Integer.parseInt(); results.
Instead, do it to addition two int values:
int result = Integer.parseInt(num1) + Integer.parseInt(num2);
And display result :
JOptionPane.showMessageDialog(null,"Your answer is " + result);
You are using num1 and num2 which are Strings instead of ans which should be your sum as an int.
Also you don't add correctly the 2 values into ans.
public static void main(String args[]){
String num1 = JOptionPane.showInputDialog(null,"Enter a number");
String num2 = JOptionPane.showInputDialog(null,"Enter another number");
int ans = Integer.parseInt(num1);
ans += Integer.parseInt(num2);
JOptionPane.showMessageDialog(null,"Your answer is " + ans);
}
Here:
num1=JOptionPane.showInputDialog(null,"Enter a number");
num2=JOptionPane.showInputDialog(null,"Enter another number");
The option pane returns strings, what you seem to understand, as you then go:
ans=Integer.parseInt(num1);
ans=Integer.parseInt(num2);
But then you use the + operator on your string results:
... +(num1+num2));
But + for strings concatenates them.
So instead of "adding" strings, you want to add the numbers, as in:
int1FromUser = Integer.parseInt(num1);
int2FromUser = Integer.parseInt(num2);
int sum = int1FromUser + int2FromUser;
That is all there is to this.
( and I took the freedom to use slightly better naming - keep in mind to use variable names that say something about the meaning of the thing they point to )
You are doing it wrong. You are adding Strings in the end and ignoring the parsed Integers.
And also you using the same integer variable for both inputs.
So that should be
int ans1=0;
int ans2=0;
...
ans1=Integer.parseInt(num1);
ans2=Integer.parseInt(num2);
And in the end
JOptionPane.showMessageDialog(null,"Your answer is " +(ans1+ans2));
+ is used in addition when using Integer or int, and it also used to concatenate two Strings. In your case num1 and num2 are Strings, and hence it is concatenating the result. So you will have to change your code to reflect following changes:
ans = Integer.parseInt(num1);
ans += Integer.parseInt(num2); // add the result of parseInt to ans
//--^---------------------------
JOptionPane.showMessageDialog(null,"Your answer is " + ans ); // another one
Or alternatively:
JOptionPane.showMessageDialog(null,"Your answer is " + (Integer.parseInt(num1) + Integer.parseInt(num2)));
I'd suggest you change the last line of your method to:
JOptionPane.showMessageDialog(null,"Your answer is " + (Integer.parseInt(num1) + Integer.parseInt(num2)));
This way, you don't need the "ans" variable (which in your code doesn't really do anything) at all. Instead, you can simply parse the int values and add them on the same line as you're writing the message.
If you want to use ans, try this:
ans = Integer.parseInt(num1) + Integer.parseInt(num2);
Then:
JOptionPane.showMessageDialog(null,"Your answer is " + ans);
I want to make a basic game where two random numbers are generated and the user has to enter the correct product.
What am I doing wrong? thanks
import java.util.Scanner;
import java.awt.*;
public class Userinput {
public static void main (String[] args) {
String firstName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
int a, b, correctAnswer;
a=(int) (Math.random()*10);
b=(int) (Math.random()*10);
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
//output information
System.out.print("Hello " + firstName + " ");
System.out.println("what is " + a +" times " + b);
String answer1 = scanner1.nextLine();
correctAnswer = a * b;
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
}
You are comparing a String (answer1) to an Integer (correctAnswer). That's comparing apples and oranges, they are never the same.
You need to either convert the String to an int:
Integer.parseInt(answer1)
which might fail if answer1 can't be parsed as an integer; or convert the int to a String:
Integer.toString(correctAnswer)
and then compare them:
Integer.parseInt(answer1) == correctAnswer // You can use == because int is primitive.
or
answer1.equals(Integer.toString(correctAnswer))
Try this:
int answer1 = scanner1.nextInt();
int correctAnswer = a*b;
if (answer1==correctAnswer) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
There were a few issues with your code, mostly related to mixing up Strings and ints. Here is a good explanation of how to compare different data types. I would recommend that you use Scanner.nextInt() to save you having to cast Strings to integers.
I would also recommend that you do not omit the braces in your if statements. It makes your code easier to read and can avoid some confusion, especially when you are just starting out with Java.
This is where the problem is:
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
Do this instead:
Integer answer = Integer.parseInt( answer1 );
if (answer1.equals(correctAnswer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
The way that it is currently written, "Incorrect!" would always be printed, because of the semi-colon on the else if. Also, it was comparing answer1 with the literal String "correctAnswer" because of the quotes. Since they're not even the same type (int and String), equals(...) returns false. I would also suggest using curly braces. It helps to alleviate some of these issues.
This question already has answers here:
Java being able to choose wether to add or subract
(3 answers)
Closed 9 years ago.
the idea is that if for example they choose * if will say wrong operator please try again but at the moment that is just looping if I choose the wrong operator and also if I choose the right operator the program needs to end , I cant seem to figure it out
my code is as follows
import java.util.Scanner;
public class Uppgift5 {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator;
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) ){
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
}
}
}
}
Your problem is here:
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) )
Assume operator is +. The value of operator does not change within the while loop, so operator will always be +, and you have an infinite loop.
Your operator will never be different. For that reason, your loops never end. You should use if instead of while
Instead of using a while loop, use a do loop that starts before you read operator from the input and only loops back if operator is not + or -. Ideally the while at the end of the do loop should come before you attempt the calculation.
Well, of course your code never ends... because you have no stopping condition. Also, your looping condition is incorrect. As long as the operator is one of those values, the loop will run. Also, you never ask for an input inside the loop. The code below should work:
import java.util.Scanner;
public class tt {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator = "";
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
while (true){
operator = input2.nextLine();
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
break;
}
}
}
}
import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.