I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."
An example output I'm given is:
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.
You generally first want to start reading input from STDIN:
Scanner in = new Scanner(System.in);
Then, I would read all parameters and afterwards perform the computation:
System.out.print("Enter the first number: ");
int left = Integer.parseInt(in.nextLine());
System.out.print("Enter the operation: ");
String operation = in.nextLine();
System.out.print("Enter the second number: ");
int right = Integer.parseInt(in.nextLine());
Now that all input is collected, you can start acting.
int result;
switch(operation)
{
case "+": result = left + right; break;
case "-": result = left - right; break;
case "*": result = left * right; break;
case "/": result = left / right; break;
case "%": result = left % right; break;
default: throw new IllegalArgumentException("unsupported operation " + operation);
}
System.out.println(left + " " + operation + " " + right + " = " + result);
Sounds like we are doing your homework! :) Make sure you learn these things or else it will eventually bite you. You can only delay the inevitable. With that "fatherly advice", here ya go.
First, you need to be able to read input from the console so that you can get the input numbers and operation. Of course, there are whole answers on this already. One link:
Java: How to get input from System.console()
Once you have the input, then you can work with it.
You will need to look at the items entered. They say you don't need to validate the numbers but you need to validate the operation. So look at the operation String variable after you got it from the console and see if it is "equalsIgnoreCase" (or just equals since these symbols don't have uppercase) to each one of the accepted operations. If it isn't equal to any of them then you should print out a message as it says. (Again with System.out.println).
You can then go into some if conditions and actually do the math if the operation equals one of the items. For example:
if(inputOperation.equalsIgnoreCase("+")){
double solution = inputInt1 + inputInt2;
//Need to do for all other operations. I didn't do the WHOLE thing for you.
}else if(NEED_TO_FILL_IN_THIS){
//Need to fill in the operation.
//You will need to have more else if conditions below for every operation
}else{
System.out.println("Your operation of '"+inputOperation+"' did not match any accepted inputs. Accepted input operations are '+','-','%','/' and '*'. Please try again.");
}
System.out.println("Your answer to the equation '"+inputInt1+" "+inputOperation+" "+inputInt2+"' is the following:"+solution);
That should get you started. Let me know if you still need further direction.
I hope that helps!
And to end with some fatherly advice: Again, it sounds like you are doing homework. This is all pretty well documented if you just know how to google. "Java get input from console". Or "Java check if String is equal to another string". Learning how to fish is so much more important than getting the fish. I suggest you do some catchup because if this is your homework and you are unsure then it seems like you are a bit behind. I don't mean to be rude. I am just trying to help you longer term.
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
Scanner f=new Scanner(System.in)
System.out.print("Enter the first number: ")
int firstNum=f.nextInt();
System.out.println();
System.out.print("Enter the operation: ")
String Op=f.nextLine();
System.out.println();
System.out.print("Enter the Second number: ")
int secNum=f.nextInt();
System.out.println();
int answ=0;
if(Op.equals("+"){
answ=firstNum+secNum;
}else if(.......){
}
hope it helps :)
To read the integers, use a Scanner
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the first number: ");
int firstNum = stdin.nextInt(); //first number
System.out.println("Enter the operation: ");
String operation = stdin.next(); //operation
System.out.println("Enter the second number: ");
int secondNum = stdin.nextInt(); //second number
doOperation(firstNum, secondNum, operation);
}
public static void doOperation(int firstNum, int secondNum, String operation)
{
if(operation.equals("+")
{
int result = firstNum + secondNum;
}
else if(...)
{
//etc
}
System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result);
}
Here is My Solution
package com.company;
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class Main {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
// write your code here
int First,Second,Resualt;
char operation;
System.out.println("Enter the first number: ");
First=scanner.nextInt();
System.out.println("Enter the operation:");
operation=scanner.next().charAt(0);
System.out.println("Enter the second number :");
Second=scanner.nextInt();
if (operation=='+'){
Resualt=First+Second;
System.out.println(First+" "+"+ "+Second+" = "+Resualt);
}
else if (operation=='-'){
Resualt=First-Second;
System.out.println(First+" "+"- "+Second+" = "+Resualt);
}
else if (operation=='*'){
Resualt=First*Second;
System.out.println(First+" "+"* "+Second+" = "+Resualt);
}
else if (operation=='%'){
Resualt=First%Second;
System.out.println(First+" "+"% "+Second+" = "+Resualt);
}
else {
System.out.println("Error");
}
}
}
Good Luck!!
Related
i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
//I used 'print' instead of 'println' just to make it look a little cleaner in the console.
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
//I use doubles for my variables just in case the user wants to divide.
System.out.print("Input your second number: ");
Scanner sc2 = new Scanner(System.in);
double num2 = sc2.nextInt();
/* I used words rather than the actual symbols for my operators just to get practice using scanners for strings.
* Until now I'd solely been using them for int variables. And also due to the small detail that before programming,
* I had no idea what a modulo was and I felt that would be confusing to a random person.
*/
System.out.println("What would you like to do with these numbers?(Add, Subtract, Multiply, Divide, or Check Divisibility): ");
System.out.println("Simply type 'check' to check the divisibility of your two numbers.");
Scanner sc3 = new Scanner(System.in);
String str1 = sc3.nextLine().toUpperCase();
/* toUpperCase to prevent the user from creating an error by typing their in put in a 'unique' way.
*It took me several failures to finally look up toUpperCase.
*/
double num3;
switch(str1) {
case "ADD":
num3 = num1 + num2;
System.out.println("The sum is: " + num3);
break;
case "SUBTRACT":
num3 = num1 + num2;
System.out.println("The difference is: " + num3);
break;
case "MULTIPLY":
num3 = num1 * num2;
System.out.println("The product is: " + num3);
break;
case "DIVIDE":
num3 = num1 / num2;
System.out.println("The quotient is: " + num3);
break;
case "CHECK":
num3 = num1 % num2;
System.out.println("The remainder is: " + num3);
break;
default:
System.out.println("Invalid input. Please ensure that two numbers were entered and that you entered a valid math operation.");
break;
}//switch statement
}//main method
}//class
How would I get my code to run again if I wanted to maybe add another number to my answer? I'm just trying to get some practice in with my Java (I'm extremely green) and I apologize in advance if my question is too broad.
Consider the following small program
boolean quit = false;
while(!quit) {
System.out.print("Enter Something:");
Scanner sc1 = new Scanner(System.in);
String input = sc1.nextLine();
if(input.compareToIgnoreCase("quit") == 0) {
quit = true;
continue;
}
System.out.println("You entered " + input);
}
In this sample we keep asking them to enter something and print it out unless that input is "quit" in that case we use the continue statement to skip the rest of the loop and go back to the top of the while loop and re-evaluate the condition for another iteration. If you entered 'quit' this will evaluate to false and stop the loop and exit the program.
Heres a sample input/output from the program. Notice there is no "You entered quit", this is because the continue statement brought us back to the top of the while loop.
Enter Something:hello
You entered hello
Enter Something:quit
Now how can you adapt this to your program? Heres a small sample of how you can do one of your inputs
double num1 = 0;
String input1 = sc1.nextLine();
if(input1.compareToIgnoreCase("quit") == 0) {
// quit was entered, leave the loop
quit = true;
continue;
}
try {
num1 = Double.parseDouble(input1);
} catch(NumberFormatException e) {
// user entered something that isnt a number, quit the program for now
// you can change this to whatever behavior you like in the future
quit = true;
continue;
}
This will likely leave you with some validation questions like "I want to have my user try again if they input an invalid number" Those are all possible using this method and it leads you in the right direction.
Remember, main() is a callable method. Instead of using a while or for loop, you could just call it again at the end of the main method method.
// Put this at the end of your main method
System.out.print("Do you want to execute again? (yes/no)");
boolean repeat = sc1.nextLine().toUpperCase().equals("YES");
if (repeat) {
main(null); // You're not using any arguments in main()
}
On a separate note, you don't need all three of sc1, sc2, and sc3. They're basically the same. You could probably use sc1 everywhere and remove sc2 and sc3 completely.
// something like this then ask if to do another run if not set flag false
boolean flag = true;
while(flag)
{
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
You should put all your logic around a while loop which will grant to you to repeat your task until a condition is reached.
Maybe you can ask to the user to insert the string "EXIT" when he wants to exit from your program.
In your case I'll do something like this:
boolean exitFlag = false;
do {
// <put your logic here>
String answer = sc3.nextLine().toUpperCase();
if (answer.equals("EXIT")) {
exitFlag = true;
}
} while(!exitFlag);
I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error
Please note the print statements, in the code segments below. My question is how come If I try to add two doubles in the print statement it prints incorrectly, but if I add them outside the print statement and store the result in a variable than I am able to print it correctly.
Why does this work and print out the correct result?
public static void main(String argsp[]){
Scanner input = new Scanner(System.in);
double first, second, answer;
System.out.println("Enter the first number: ");
first = input.nextDouble();
System.out.println("Enter the second number: ");
second = input.nextDouble();
answer = first + second;
System.out.println("the answer is " + answer);
}
Why does this print out the wrong result?
public static void main(String argsp[]){
Scanner input = new Scanner(System.in);
double first, second;
System.out.println("Enter the first number: ");
first = input.nextDouble();
System.out.println("Enter the second number: ");
second = input.nextDouble();
System.out.println("the answer is " + first+second);
}
It's because what you're basically doing in that second part is:
System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second));
That's how the compiler interprets it. Because the + operator when you are giving a String to a method is not a calculation but a concatenation.
If you want it done in one line, do it like this:
System.out.println("the answer is " + (first + second)); //Note the () around the calculation.
In case of doubt with the precedence of operators, just use parens. It is also clearer to read.
System.out.println("the answer is " + (first+second));
In the second case, the doubles are converted to Strings because the + is considered String concatenation. To work around this, use parentheses to group expressions that should perform numeric calculations:
System.out.println("the answer is " + (first + second));
I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case