How to multiply Roman Number string with a double in Java? - java

i am new to a java program and i have a homework where when i get input from a user as an string, i have to convert it to a double and multiple it with a .11111 using a switch decision structure.
A string input from user has to be a number in roman numeral which is I, II, III, IV, and so on....
//This is my program
package practiceNum;
import java.util.Scanner;
public class practiceNum{
class stastic void main(String[] args){
String num_In_Roman; //declare a string
Scanner keyboard = new Scanner(System.in); //read input words
System.out.println("Enter a roman numerals from I to X: "); //asking user input
num_In_Roman = keyboard.nextLine();
switch(num_In_Roman){
case "I":
break;
case "II":
break;
//and so on until 10 (X) in roman numerals.
default:
System.out.println("Invalid Number!");
}
//end of body program here
}
}
Here's what i did to calculate my math but still giving me an error.
Double value = Double.parseDouble(num_In_Roman); //convert string into double
case "I":
value *= .111111;
System.out.println(value);
break;
someone help please.

This is the bad way, but this is what you can do:
case "I":
value = 1 * .111111;
System.out.println(value);
break;
case "II":
value = 2 * .111111;
System.out.println(value);
break;

Related

Why my binary to decimal conversion is not working in java?

I have this method where it converts a binary input from a user to decimal value.
Main Method:
public static void main(String args[])
{
String inputByUserString=""; //number input by the player
int inputByUserInteger;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number"); //getting the input
inputByUserString=sc.nextLine();
inputByUserInteger=Integer.parseInt(inputByUserString);
and then I create a switch case where there is more options for conversion like Decimal number to Binary number etc...
Then in that switch I call a method:
int binaryToDecimalNumberVariable=obj1.binaryToDecimalConversion(inputByUserInteger);
System.out.println("Binary Number:"+inputByUserInteger);
System.out.println("Decimal Number:"+binaryToDecimalNumberVariable);
Method for binary to decimal conversion:
public int binaryToDecimalConversion(int inp) //to convert binary number into decimal number
{
int a1;int a2=0;int a3 = 0;
while(inp>0)
{
a1=inp%10;
a1=inp/10;
a3=(int)(a3+(a1*(Math.pow(2,a2)))); //result
a2++;
}
return a3;
}
The whole switch case:
System.out.println("What type of conversion do you want?");
System.out.println("1)Decimal number to Binary number");
System.out.println("2)Binary number to Decimal number");
System.out.println("3)Decimal number to Octal number");
System.out.println("4)Octal number to Decimal number");
System.out.println("5)Decimal number to Hexadecimal number");
System.out.println("6)Hexadecimal number to Decimal number");
System.out.println("7)Octal number to Hexadecimal number");
System.out.println("8)Hexadecimal number to Octal number");
int choice=sc.nextInt();
switch(choice)
{
case 1: //Decimal number to Binary number
break;
case 2: //Binary number to Decimal number
int binaryToDeci=obj1.binaryToDecimalConversion(inputByUserInteger);
System.out.println("Binary Number:"+inputByUserInteger);
System.out.println("Decimal Number:"+binaryToDeci);
break;
case 3: //Decimal number to Octal number
break;
case 4: //Octal number to Decimal number
break;
case 5: //Decimal number to Hexadecimal number
break;
case 6: //Hexadecimal number to Decimal number
break;
case 7: //Octal number to Hexadecimal number
break;
case 8: //Hexadecimal number to Octal number
break;
default:
System.out.println("Invalid Input");
} //switch close
It shows no error while compiling but when I execute it,it just stucks.
Error that is showing when I execute it:
So, help me.
To expand on my comment, the correct way to handle your requirements:
String myBinaryNr = sc.next();
int myNr = Integer.parseInt(myBinaryNr, 2);
String myDecimalNr = Integer.toString(myNr, 10);
The last 10 is optional, since it is the default.
If it's getting stuck, it probably hasn't detected an input and it's awaiting for it. To confirm this, I would add a
System.out.println("Test" + choice);
just under the choice input, so it would be like this:
int choice = sc.nextInt();
System.out.println("Test" + choice);
switch(choice){...}
If it doesn't print correctly, then you have found your issue. It may have something to do with the System.in
Never mind,I just have to do this and it solves the problem.
public int binaryToDecimalConversion(int inp) //to convert binary number into decimal
{
int a1;int a2=0;int a3 = 0;
while(inp>0)
{
a1=inp%10;
a3=(int)(a3+(a1*(Math.pow(2,a2)))); //result
a2++;
inp=inp/10;
}
return a3;
}

Command line calculator with multiple input numbers and operators?

Newbie to Java; I've created a Command line calculator that gets a double from user and gets one operation symbol and gets another double from user and the calculates the amount.
This is my code.
import java.util.Scanner;
public class forthProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double numb1, numb2, add, subtract, multiply, divide;
char operation;
while (true) {
System.out.println("Calculate: ");
numb1 = in.nextDouble();
operation = in.next().charAt(0);
numb2 = in.nextDouble();
switch (operation) {
case '+':
add = numb1 + numb2;
System.out.println(add);
break;
case '-':
subtract = numb1 - numb2;
System.out.println(subtract);
break;
case '*':
multiply = numb1 * numb2;
System.out.println(multiply);
break;
case '/':
divide = numb1 / numb2;
System.out.println(divide);
break;
}
}
}
}
What I want to figure out is how to be able to get multiple numbers from users and do multiple operations.
for example a user could type (3+4)*4/6= and get an answer.
Also I would like to implement the bedmas in the new code.
I'll appreciate your guidance.
In order to implement PEMDAS and do multiple operations, you will need to keep all input until the user sends in '='. One way to do this is reverse polish notation. Just transform the string to RPN and then run through the equation.

Invalid constant character when using switch/case?

I cannot seem to make my code work properly. I need to find the area of the square and add the units of measurement depending on what the user uses either in for inch, m for meter, cm for centimeter, and ft for feet.
public static void main (String[] args)
{
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
double side1 = sc.nextDouble();
while (side1 < 0)
{
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
side1 = sc.nextDouble();
}
char unitsMeasurement;
// prompt the user to enter the measurement unit
char units = Character.toUpperCase(status.charAt(0));
String unitsMeasurement = "";
**{
switch(units)
{
case "in":
unitsMeasurement = "inch"; break;
case "cm":
unitsMeasurement = "centimeter"; break;
case "ft":
unitsMeasurement = "feet"; break;
case "m":
unitsMeasurement = "meter"; break;
default:System.out.println("Invaild unit"); break;
}**
//Area of Square = side*side
double area = side1*side1;
**System.out.println("Area of Square is: "+area, +unitsMeasurement+);**
}
}
}
Your main problem is, that you are using a switch-case-statement on a char while all your cases are based on a String. That doesn't work together.
Some other problems are that status is never defined, therefore units can't have a value at all.
I'm not quite sure what you are trying to achieve, but I assume the following:
The user inputs the length of a square with a unit (abbreviated). The program calculates the area of the square and outputs it together with the unit (unabbreviated).
Sample input:
5cm
Sample output:
Area of square is: 25 centimeter^2
Keep in mind that an area has a squared length unit!
Based on that, here is some working code:
public static void main (String[] args) {
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
String input = sc.nextLine();
//Remove anything but digits
double side1 = Double.parseDouble(input.replaceAll("\\D+",""));
//Remove all digits
String unit = input.replaceAll("\\d","");
System.out.println(side1);
System.out.println(unit);
while (side1 < 0) {
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
input = sc.nextLine();
//Remove anything but digits
side1 = Double.parseDouble(input.replaceAll("\\D+",""));
}
switch(unit) {
case "in":
unit = "inch";
break;
case "cm":
unit = "centimeter";
break;
case "ft":
unit = "feet";
break;
case "m":
unit = "meter";
break;
default:
System.out.println("Invaild unit");
break;
}
double area = side1*side1;
System.out.println("Area of Square is: " + area + " " + unit + "^2");
}

Java validation error from user input

I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated.
If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors
Java
package calculator;
import java.util.Scanner;
public class calculator {
/**
* #param args
*/
public static void main(String[] args) {
double n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
System.out.println("Enter second number");
n2 = scannerObject. nextDouble();
Scanner op = new Scanner(System.in);
System.out.println("Enter your operation");
operation = op.next();
switch (operation) {
case "+":
System.out.println("Your answer is " + (n1 + n2));
break;
case "-":
System.out.println("Your answer is " + (n1 - n2));
break;
case "/":
System.out.println("Your answer is " + (n1 / n2));
break;
case "*":
System.out.println("Your asnwer is " + (n1 * n2));
break;
default:
System.out.println("I do not know!");}
}
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
}
and these are the error messages I get:
Errors
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at calculator.calculator.main(calculator.java:14)
I've tried so many different things but can't get it to work as I want it.
Can anyone be of any assistance here?
Thanks for reading
This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.
You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Taken from documention on Scanner
double nextDouble()
Returns the next token as a long. If the next token is not a float or
is out of range, InputMismatchException is thrown.
I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.
You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)
It seems that you are not entering any integer as input.
You can solve this by handling the exception this way :
try {
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine();
}
catch (InputMismatchException e) {
input.nextLine();
}
Your issue is at,
scannerObject. nextDouble();
You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input");
}
Then you may want to create a loop to get the input again and agin until valid input is detected.
Edit
You'll need to,
import java.util.InputMismatchException;
Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.
boolean notValidInput = true;
while(notValidInput) {
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
notValidInput = false;
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input. Please try again!");
}
}

Begining Java student [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a program where i have to use methods to count my string, .upper and lower using a switch statement. My code is not showing any errors can someone help.
import java.util.*;
public class Strings
{
public static void main(String[] args)
{
String selection;
Scanner keyboard = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
selection = keyboard.nextLine();
switch(selection.charAt(0))
{
case 1:
numberOfWords(selection);
break;
case 2:
allCapitals(selection);
break;
case 3:
allLowers(selection);
break;
case 4:
reverseOrder(selection);
break;
}//ends switch
}
/*public static void menuMethod(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
}
*/
public static void numberOfWords(String selection)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
input = keyboard.nextLine();
// Display the number of words.
System.out.println("That string has " + wordCount(input) + " words in it.");
}
public static int wordCount(String str)
{
StringTokenizer strTok = new StringTokenizer(str);
return strTok.countTokens();
}
public static void allCapitals (String str)
{
String input;
String capInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
capInput = input.toUpperCase();
System.out.println("Your capital case string = \n" + capInput);
}
public static void allLowers (String str)
{
String input;
String lowerInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
lowerInput = input.toUpperCase();
System.out.println("Your lower case string = \n" + lowerInput);
}
public static void reverseOrder (String str)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter something: ");
input = keyboard.nextLine();
// Display it backwards.
backward(input);
}
public static void backward(String str)
{
for (int i = str.length() - 1; i >= 0; i--)
System.out.print(str.charAt(i));
System.out.println();
}
}
Please use this code for switch
switch(selection.charAt(0))
{
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;
}//ends switch
replace your switch condition to
switch(Integer.parseInt(selection))
{
//your code
}
instead of
switch(selection.charAt(0))
{
//your code
}
if you use charAt(0) your checking condition must be like that because that method returns a char value
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;
You haven't said what is wrong with the program output. Explaining your problem as thoroughly as possible will help you get a good answer quickly.
As for possible problems:
Your allLowers() method is using toUpperCase(). As a good design practice, try to copy paste code as little as possible, since copy/pasting code implies that there could be a function that does the same thing.
You are never actually checking for an input of -1. All you would do in your current method (if you were to check for the exit condition) is check for the - sign as that is the first character, rather that the entire -1 string, which could easily lead to bugs if you expand the program.

Categories