Create a java program that will do the following:
a) Read three inputs from the keyboard,
• two input numbers each being a single digit (0…9)
• one character representing one of five operations : + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation)
b) output the description of the operation in plain English as well as the numeric results
import java.util.Scanner;
public class EnglishCalc {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int number1 = input.nextInt();
System.out.println("Enter second number");
int number2 = input.nextInt();
System.out.println("Enter operation: +,-,*,/,^");
String operation = input.next();
int output = 0;
if(number1 < 0 || number1 > 9 || number2 < 0 || number2 > 9) {
System.out.println("Number should be between 0 and 10");
}
else if (operation.equals("+"))
{
output = number1 + number2;
System.out.println("Sum of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("-"))
{
output = number1 - number2;
System.out.println("Subtraction of "+number2+" from "+number1+" is: " +output);
}
else if (operation.equals("*"))
{
output = number1 * number2;
System.out.println("Product of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("/"))
{
if(number2 == 0) {
System.out.println("You cannot divide by 0");
} else {
output = number1/number2;
System.out.println("Division of "+number1+" by "+number2+" is: " +output);
}
}
else if(operation.equals('^'))
{
output = Math.pow((double)number1 , (double)number2);
System.out.println("Value of "+num1+" raised to power of "+num2+" is: " +output);
} else {
System.out.println("Invalid input");
}
}
}
for pow. i tried casting wont work. and if i dont cast, it wont accept int. must be double.
Use
s1.equals(s2)
to compare strings, instead of using:
s1 == s2
This happens because == is used to compare object references (if the are the same object), so it doesn't compare the 'contain' of that object, in this case a String.
Edit
To print each number in 'words', you could use an array:
String[] numbers = {"zero", "one", "two", ... };
and then use them as:
System.out.println(numbers[2] + " plus " + numbers[5] + ...);
Related
I'm trying to solve this program using recursive function which is needed for our program. The program is converting a decimal number system from a decimal 16 divided to a base of 2 using recursion, but my problem is that instead of the expected output of 10000 somehow it is reversed into 00001.
public static void main(String[] args) {
int decimalValue = 0;
int targetBase = 0;
while (decimalValue != -1){
Scanner input = new Scanner(System.in);
System.out.print("Decimal value: ");
decimalValue = input.nextInt();
if (decimalValue == -1){
System.out.println("Thank you for using the program. bye!");
System.exit(0);
}
while (targetBase < 2 || targetBase > 16){
System.out.print("Target base: ");
targetBase = input.nextInt();
}
System.out.print("Value of " + decimalValue + " in base " + targetBase + " is ");
recursionFunction(decimalValue, targetBase);
targetBase = 0;
}
}
public static void recursionFunction(int Decimal, int Base){
int result,test1;
if (Decimal == 0) {
System.out.println(" " );
return;
}
result = Decimal / Base;
System.out.print(Decimal % Base);
recursionFunction(result, Base);
}
I am doing a Palindrome number sequence. I've got the math set up, but I'm having trouble nesting my if statements only showing one answer.
I've attempted to remove the 'if' from the 'else if' but then java doesn't recognize. The output doesn't provide the "Not 5 digits" and when I enter 5 digits that are a Palindrome it sends an output both True and False instead of just true. However it works perfect for a false 5 digit number input. Can I have some help on how to nest appropriately is what I'm asking for or an example of a good explanation to help me achieve the results as I've been to quite a few sites, but most are too simple and lack examples to compare.
import java.util.Scanner;
public class Palindrome
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
int userNumber = input.nextInt();
System.out.println("Input value: " + "\t" + userNumber);
//User input incorrect amount of digits
if (userNumber >= 100000 && userNumber <= 9999)
{
System.out.println("Not 5 digits.");
}
else if(userNumber < 100000 && userNumber > 9999)
{
int Number5 = (userNumber/10000) % 10;
int Number4 = (userNumber/1000) % 10;
int Number3 = (userNumber /100) % 10;
int Number2 = (userNumber/10) % 10;
int Number1 = userNumber % 10;
//Conditions are met for Palidrome Number
if(Number1 == Number5 && Number2 == Number4)
{
System.out.println("Judgement: " + "\t" + "\t" + "True");
}
//Conditions are not met for Palidrome Number
else if (Number1 != Number5 || Number2 !=Number4);
{
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}
}
The results should show true, false, or not 5 digits
There is no number that is >= 100000 and <= 9999, this is why you never see Not 5 digits.
You must change that condition to:
if (userNumber <= 9999 || userNumber > 99999)
and change:
else if(userNumber < 100000 && userNumber > 9999)
to a simple
else
because if the code reaches the else part then userNumber < 100000 && userNumber > 9999 is always true.
The same applies to
else if (Number1 != Number5 || Number2 !=Number4);
(Note: the ; at the end is wrong and a source of serious headaches)
which must be changed to:
else
This statement:
int Number3 = (userNumber / 100) % 10;
is redundant as the value of Number3 is not useful in this case.
So your code should be simplified like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
int userNumber = input.nextInt();
System.out.println("Input value: " + "\t" + userNumber);
if (userNumber <= 9999 || userNumber > 99999) {
System.out.println("Not 5 digits.");
}
else {
int Number5 = (userNumber / 10000) % 10;
int Number4 = (userNumber / 1000) % 10;
int Number2 = (userNumber / 10) % 10;
int Number1 = userNumber % 10;
if (Number1 == Number5 && Number2 == Number4) {
System.out.println("Judgement: " + "\t" + "\t" + "True");
} else {
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}
This can work:
import java.util.Scanner;
import java.lang.*;
public class Main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
String userNumber = input.next();
System.out.println("Input value: " + "\t" + userNumber);
//User input incorrect amount of digits
if (userNumber.length()!=5)
{
System.out.println("Not 5 digits.");
}
else{
//Conditions are met for Palidrome Number
if(new StringBuilder(userNumber).reverse().toString().equals(userNumber))
{
System.out.println("Judgement: " + "\t" + "\t" + "True");
}
//Conditions are not met for Palidrome Number
else
{
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}
}
Your 2nd else if statement is redundant, and you have an extra semicolon in your last if statement.
I'm really new to java and I cannot find a way around this. I want to make a program that tells you that a number is either positive or negative, regardless if it is int or double. But after the program is executed, I want it to loop and ask again for input from the user, to execute the code again and again and again, as long as there is user input. Can I do that in java?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
}
}
Here is a one of the approach which is good start for you to understand what wonders pattern matching can do in Java and it can be improved by testing it against exhaustive data points.
This also shows how to use while-loop, overloading methods and ternary operator instead of nested if-then-else.
As you are learning, you should also use debugging feature of editors and also use system.out.println to understand what code is doing.
I am ending the program when user presses just enter (empty string).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = "Input your number: ";
System.out.print(userInput);
String input = scanner.nextLine();
// look for integer (+ve, -ve or 0)
if (input.matches("^-?[0-9]+$")) {
int z = Integer.parseInt(input);
System.out.println(display(z));
// look for double (+ve, -ve or 0)
} else if (input.matches("^-?([0-9]+\\.[0-9]+|[0-9]+)$")) {
double z = Double.parseDouble(input);
System.out.println(display(z));
// look for end of program by user
} else if (input.equals("")) {
System.out.println("Good Bye!!");
break;
// look for bad input
} else {
System.out.println("Hey! Only numbers!");
}
}
scanner.close();
}
// handle integer and display message appropriately
private static String display(int d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
// handle double and display message appropriately
private static String display(double d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
}
Sample Run:
Input your number: 0
0 is equal to 0
Input your number: 0.0
0.0 is equal to 0
Input your number: -0
0 is equal to 0
Input your number: -0.0
-0.0 is equal to 0
Input your number: 12
12 is positive
Input your number: -12
-12 is negative
Input your number: 12.0
12.0 is positive
Input your number: -12.0
-12.0 is negative
Input your number: 12-12
Hey! Only numbers!
Input your number: ---12
Hey! Only numbers!
Input your number:
Use this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Console console = new Console();
while(true) {
// Take your input
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
// Ask for exit
System.out.print("Want to quit? Y/N")
String input = console.readLine();
if("Y".equals(input))
{
break;
}
}
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please select your operator:\n"
+ "1 for +\n" +
"2 for -\n" +
"3 for *\n" +
"4 for %\n" +
"");
operator = myScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" +
"y for yes\n" +
"n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput=='n') ask=false;
}
}
}
i got trouble in my switch case
if i press any number or letter somthing like 5 or 6 or... it should print you chose wrong operator.
i think problem is in my default but i don't know where is it?
Just reorder your code like this
`public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int operator;
double number1, number2, result;
boolean ask = true;
while (ask) {
System.out.println("please enter your first number");
Scanner numberScanner = new Scanner(System.in);
number1 = numberScanner.nextDouble();
System.out.println("please enter your second number");
Scanner numberScanner2 = new Scanner(System.in);
number2 = numberScanner2.nextDouble();
System.out.println("please select your operator:\n"
+ "1 for +\n"
+ "2 for -\n"
+ "3 for *\n"
+ "4 for %\n"
+ "");
operator = myScanner.nextInt();
switch (operator) {
case 1:
result = number1 + number2;
System.out.println("result is:" + result);
break;
case 2:
result = number1 - number2;
System.out.println("result is:" + result);
break;
case 3:
result = number1 * number2;
System.out.println("result is:" + result);
break;
case 4:
result = number1 / number2;
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("you chose " + operator + " operator babe");
System.out.println("do yo want to continue?\n"
+ "y for yes\n"
+ "n for no\n");
char askInput = myScanner.next().charAt(0);
if (askInput == 'n') {
ask = false;
}
}
}`
and you'll be fine
as for my comment, if you want to validate the input the user does (for the option) before having the user input another 2 numbers, than, yeah you should actually programm it that way that the validation goes RIGHT AFTER the first userinput. Here´s a slightly corrected version of your code.
public static void main(String[] args) {
int operator;
double result;
boolean ask = true;
Scanner numberScanner = new Scanner(System.in);
while (ask) {
System.out.println(
"please select your operator:\n" + "1 for +\n" + "2 for -\n" + "3 for *\n" + "4 for %\n" + "");
operator = numberScanner.nextInt();
System.out.println("you chose " + operator + " operator babe");
// Here was your "Mistake". You instantly started asking the user for another input,
// but actually wanted to ahve the switch statment here
switch (operator) {
case 1:
result = get_num1(numberScanner) + get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 2:
result = get_num1(numberScanner) - get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 3:
result = get_num1(numberScanner) * get_num2(numberScanner);
System.out.println("result is:" + result);
break;
case 4:
result = get_num1(numberScanner) % get_num2(numberScanner);
System.out.println("result is:" + result);
break;
default:
System.out.println("you chosen the wrong operator babe :)");
break;
}
System.out.println("do yo want to continue?\n" + "y for yes\n" + "n for no\n");
char askInput = numberScanner.next().charAt(0);
if (askInput == 'n')
ask = false;
}
}
public static double get_num1(Scanner scanner) {
System.out.println("please enter your first number");
return scanner.nextDouble();
}
public static double get_num2(Scanner scanner) {
System.out.println("please enter your second number");
return scanner.nextDouble();
}
simply you could validate the operator while you assign it with the input.
for example use if condition and check whether its between 1 and 5 and if not print whatever you want
2 things:
you dont need 2 scanners using only one will be enough
the code is behaving so because you go into the switch case AFTER asking the numbers you want to operate...
some condition like:
operator = myScanner.nextInt();
if (operator < 1 || operator > 4) {
}
may help....
I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}