Converting roman numerals to arabic - java

I'm new to Java and I need to write a program that converts roman numerals to arabic numbers.
I cannot use some functions because I'm not allowed to change the begging neither the end of the given code. I need to do everything inside the the public static void main function.
I started to search on Google and started to code. From now, I can convert only "one-letter" numerals (as X, I, V...) to arabic numbers but I cannot do this to more than elaborated numerals (XI, CCC, IX, IV...).
Can someone help me? I'm really new to Java. It's my first program language and I'm struggling to understand it.
Here is my code:
import java.util.Scanner;
class Roman {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = {1000, 500, 100, 50, 10, 5, 1 };
String symbols = "MDCLXVI";
/*******************************************
* Complete your program
*******************************************/
System.out.print("Enter a roman numeral");
final int MAX = 3999;
Scanner keyb = new Scanner(System.in);
String roman = keyb.next();
roman=roman.toUpperCase();
if(roman.matches(".*[0-9].*") || !roman.matches("[M|D|C|L|X|V|I]*")){
System.out.println("Impossible to convert. Wrong roman numeral");
}
int i = 0; //position in the string romain
int arabic = 0; // Arabic numeral equivalent of the part of the string that
// has been converted so far
int number;
while (i < roman.length()){
char letter = roman.charAt(i); // letter at the current position in the string
if (letter == 'I'){
number = 1;
} else if (letter == 'V'){
number = 5;
} else if (letter == 'X'){
number = 10;
} else if (letter == 'L'){
number = 50;
} else if (letter == 'C'){
number = 100;
} else if (letter == 'D'){
number = 500;
} else if (letter == 'M'){
number = 1000;
} else {
number = -1;
}
i++; // Move on to next position in the string
if (i==roman.length()){
// There is no letter in the string following the one we have just processed.
// So just add the number corresponding to the single letter to arabic.
arabic += number;
} else {
// Look at the next letter in the string. If it has a larger Roman numeral
// equivalent than number, then the two letters are counted together as
// a Roman numeral with value (nextNumber - number).
number = roman.charAt(i);
int nextNumber = number;
if(nextNumber > number){
// Combine the two letters to get one value, and move on to next position in string.
arabic += (nextNumber - number);
i++;
} else {
// Don't combine the letters. Just add the value of the one letter onto the number.
arabic += number;
}
}
System.out.println(number);
} // end while
/*******************************************
* Do not change after this line.
*******************************************/
}
}

I would suggest using an enumeration for your individual roman numerals. That makes the code nicely encapsulated.
public enum Roman {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private Roman(int value) {
this.value = value;
}
public int toInt() {
return value;
}
}
Converting a single roman numeral to an integer becomes trivial. For example:
Roman.valueOf("X").toInt();
The only complex bit is coping with "IX" and "XC" type of values. The easy way to identify these is that they are the only time when the numerals are not in descending order of value. Checking for this can be added as methods to the enum itself (to continue encapsulation):
public enum Roman {
public boolean shouldCombine(Roman next) {
return this.value < next.value;
}
public int toInt(Roman next) {
return next.value - this.value;
}
}
Now putting it all together:
List<Roman> romans = new ArrayList<>();
input.chars().mapToObj(Character::valueOf)
.map(Roman::valueOf).forEach(romans::add);
int value = 0;
while (!romans.isEmpty()) {
Roman current = romans.remove(0);
if (!romans.isEmpty() && current.shouldCombine(romans.get(0))
value += current.toInt(romans.remove(0));
else
value += current.ToInt();
}
The first part of this code uses Java 8 features to convert the string to roman numerals. Let me know if you find that confusing and I'll convert it to traditional iteration.

Here is one way to do it:
import java.util.Scanner;
class Roman {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = { 1000, 500, 100, 50, 10, 5, 1 };
String symbols = "MDCLXVI";
/*******************************************
* Complete your program
*******************************************/
System.out.print("Enter a roman numeral: ");
final int MAX = 3999;
Scanner keyb = new Scanner(System.in);
String roman = keyb.next();
keyb.close(); // don't want a resource leak
roman = roman.toUpperCase();
if (roman.matches(".*[0-9].*") || !roman.matches("[M|D|C|L|X|V|I]*")) {
System.out.println("Impossible to convert. Wrong roman numeral");
}
int i = 0; // position in the Roman string
int current = 0; // the current Roman numeral character to Arabic
// conversion
int previous = 0; // start previous at zero, that way when
// current is greater than previous in the first
// run, nothing will be subtracted from current
int arabic = 0; // Arabic numeral equivalent of the part of the string
// that has been converted so far
while (i < roman.length()) {
char letter = roman.charAt(i); // letter at the current position in
// the string
// switch statement is easier to read than if - else if - else
switch (letter) {
case ('I'):
current = 1;
break;
case ('V'):
current = 5;
break;
case ('X'):
current = 10;
break;
case ('L'):
current = 50;
break;
case ('C'):
current = 100;
break;
case ('D'):
current = 500;
break;
case ('M'):
current = 1000;
break;
}
if (current > previous) {
// subtract previous * 2 because previous was added to arabic
// once already
arabic += current - (previous * 2);
} else {
// if current is less than or equal to previous then add it to
// arabic
arabic += current;
}
previous = current; // set previous equal to current to check
// for less-than on next iteration
i += 1; // move on to next position in the string
} // end while
// print the Arabic conversion after the loop is done
System.out.println("Arabic: " + arabic);
/*******************************************
* Do not change after this line.
*******************************************/
}
}
In your code, the conditionals after i++ are not necessary since the while(i < roman.length()) conditional stops the loop once i >= roman.length().
Yet another way to do it: switch out the while loop with a for loop and a nested for loop. The outer for loop iterates over each character in the Roman numeral string. The inner for loop iterates over each character in the symbols string. If there is a match between the Roman numeral character and the symbols character, then current is set to the corresponding index in numbers and the inner loop breaks.
for(int i = 0; i < roman.length(); i++) {
for(int s = 0; s < symbols.length(); s++) {
if(roman.charAt(i) == symbols.charAt(s)) {
current = numbers[s];
break;
}
}
if (current > previous) {
// subtract previous * 2 because previous was added to arabic
// once already
arabic += current - (previous * 2);
} else {
// if current is less than or equal to previous then add it to
// arabic
arabic += current;
}
previous = current; // set previous equal to current to check
// for less-than on next iteration
}

This is "one look ahead" in Formal Languages. The only way to solve this problem is to compare position 0 to the next char. If value is less than, value is substracted from the acccumulator, if >=, it is added.

Related

Checking if String entered is a binary numer, getting incorrect output

I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number. I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.
As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction. Here is my code (after trying to make it work with Strings rather than integers):
import java.util.*;
public class BinaryHW {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
//the method I used to check whether or not user entered a binary
//number requires changing the value of 'bin'.
//Therefore, 'origBin' set equal to 'bin' for later use.
String origBin = bin;
int count = 0;
boolean isBinary = true;
/* if bin = 0, then this loop will be skipped because
* 0 is a binary number and need not be checked.
*/
while (Integer.parseInt(bin) != 0) {
int lastDigit = bin.charAt(bin.length() - 1);
if (lastDigit > 1) {
System.out.println("Number entered is not binary.");
isBinary = false;
break;
} else {
bin = bin.substring(bin.length() - 2);
}
}
//Again, the method I used to count the 1s in the bin number
//requires changing the value of origBin, so origBin2 is introduced
String origBin2 = origBin;
for (int i = 0; i < origBin.length(); i++) {
if (origBin.charAt(origBin.length() - 1) == 1) {
count ++;
origBin2 = origBin.substring(origBin2.length() - 2);
} else {
origBin2 = origBin.substring(origBin2.length() - 2);
}
}
if (isBinary)
if (count == 1)
System.out.println("There is "
+ count + " 1 in the binary number entered.");
else
System.out.println("There are "
+ count + " 1s in the binary number entered.");
}
}
I think you are overcomplicating things... simply iterate through your binary string, and keep track of the number of 1's reached. If a number other than 0 or 1 is found, report that input is a non-binary number. Below is a snippet which accomplishes this:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
int oneCount = 0;
boolean validBinaryNum = true;
for (int i = 0; i < bin.length() && validBinaryNum; i++) {
char currentChar = bin.charAt(i);
if (currentChar == '1') oneCount++;
else if (currentChar != '0') {
validBinaryNum = false;
}
}
if (validBinaryNum && bin.length() != 0) {
System.out.println("Number of 1's: " + oneCount);
} else {
System.out.println("Number is not binary");
}
}

Can't locate Java substring in for loop

I'm trying to make a calculator app and I have a string for the final equation inputted.
"983+388+12"
How I'm solving is by first identifying where the operator is. After this I loop backwards and forwards trying to find the 2 numbers and then I add them. So I would find the plus symbol then 983 and 388 and add them. I'm having trouble matching the previous/next numbers in relation to the add symbol.
public static void main(String[] args)
{
int plus=0;
String string="983+388+12";
//locating Plus symbol
for(int i=0;i<string.length();i++)
{
if(string.charAt(i)=='+')
{
plus=i;
}
}
//locating next number (should be 388)
for(int i=plus+1;i<string.length();i++)
{
if(string.charAt(i)=='+' || string.charAt(i)=='-')
{
String nextNumber=string.substring(plus+1, i-1);
System.out.println(nextNumber);
break;
}
}
I am not getting anything returned as a value for nextNumber
When you find the + in the first loop, you don't stop scanning the string. This results in plus marking the location of the last +, which is after the 388 and before the 12. The second loop never finds a + or a - after the last +, so nothing is ever printed. When you find the first +, break out of the loop.
Also, to avoid just 38 being found, correct your substring call, where the ending index is exclusive.
String nextNumber = string.substring(plus + 1, i);
Try using only one loop, see below (working example). I didn't break anything up into smaller methods.
public static void main(String[] args) {
String string="983+388+12";
String numberStr="0";
int lastSignPos = 0;
int signPos=0;
char sign = '+';
int total=0;
//locating Plus symbol
for(int i=0; i < string.length(); i++) {
if(string.charAt(i)=='+' || string.charAt(i)=='-') {
lastSignPos = signPos;
signPos = i;
numberStr = "0";
if (lastSignPos == 0){
// first number in series
numberStr = string.substring(0,signPos);
} else {
numberStr = string.substring(lastSignPos + 1, signPos);
}
sign = '+';
if (string.charAt(lastSignPos)=='-'){
sign = '-';
}
total += Integer.parseInt(sign + numberStr);
}
}
// take care last number
numberStr = string.substring(signPos+1);
sign = '+';
if (string.charAt(signPos)=='-'){
sign = '-';
}
total += Integer.parseInt(sign + numberStr);
System.out.println(total);
}
You can try something like this :
String example = "123+456+678";
String delim = "+";
StringTokenizer st = new StringTokenizer(example,delim);
while (st.hasMoreElements()) {
System.out.println("StringTokenizer Output: " + st.nextElement());
}

Roman Numeral to Integer: what is wrong with my code

So I'm trying to make a converter from roman numerals to integers. What I have so far is this:
public int toNumber(String n){
int number = 0;
int first = 1;
int last = 0;
String substring = n.substring (last, first);
while(substring.equals("I")){
number = number+1;
last = last +1;
first=first +1;
}
while(substring.equals("V")){
number = number+5;
last = last +1;
first=first +1;
}
return number;
}
Obviously I only have I and V in right now, but when I make a tester class to try this out, it returns nothing and keeps letting me put in in a new line.
For the record, here is my tester class
import java.util.Scanner;
public class Tester{
public static void main (String[] args){
RomanNumeralConverter quantity = new RomanNumeralConverter();
Scanner user_input = new Scanner(System.in);
//this is for roman to number
System.out.println("input roman numeral");
String j = user_input.nextLine();
int g = quantity.toNumber(j);
System.out.println(g);
}
}
I'm almost entirely certain that it's a logic problem, but I have no idea what and I feel like I've tried everything I can think of
Your problem is a loop like this:
while(substring.equals("I")) {
number = number+1;
last = last +1;
first=first +1;
}
If the program enters that loop, it will stuck there, because you're not changing the value of substring. Therefore substring.equals("I") will always return true and the only way to stop that loop is terminating the application.
A better way to convert the entered String could be this:
public int toNumber(String n) {
int number = 0;
for (char chr : n.toUpperCase().toCharArray()) {
switch(chr) {
case 'I': number += 1;
break;
case 'V': number += 5;
break;
default: break;
}
}
return number;
}
It converts the provided String to uppercase (viii -> VIII) to avoid checking both cases of every char and converts it into a char array. This array will be used in a foreach loop that takes every single entry of it and tests it in a switch block. Every supported roman numeral has his own case there to increment number accordingly. Currently it supports I and V like in your code. Btw, number += 1 is just a short version of number = number + 1.
After that loop, it returns the converted integer value.

binary to base10 in java with main method and TWO classes/method (boolean and

I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}

Reading in a string, checking the string, and outputting the number

I'm having a huge problem here. Basically what i have to do is have a user enter a number... the program then takes the number, reads if it's negative or positive. If negative it sets the previously false negval to true and moves on. it then reads the number again, checking for leading zeros, if there are any it removes them. It then takes what is left and checks to see if the string is less than the max amount of characters aloud, if it is then it loops to count the spaces, while it counts the spaces it also makes sure they are digits . if the string is bigger than the allowed amount of characters the program stops checks and prints a 0
my problem is that it keeps jumping to the 0 output even though the string length is a valid length
here is what i have.
String snum;
System.out.print("Please enter a number here : ");
snum = console.next();
System.out.println(getIntnum(" The number entered was: "+snum));
Other generic stuff
final String maxInt = "2147483648";
final String minInt = "-2147483648";
boolean negval = false;
int n;
int count;
int num = 1;
int value;
if(snum.charAt(0) == '-' || snum.charAt(0) == '+')
{
if(snum.charAt(0) == '-')
{
negval = true;
}
else
{
snum = snum.substring(1, snum.length());
}
}
while (snum.charAt(0) == '0')
{
snum = snum.substring(1, snum.length());
}
n = snum.length( );
if (n < 10)
{
count = 0;
if (count < n)
{
if (Character.isDigit(snum.charAt(count)))
count++;
}
}
else
{
num = 0;
}
if(maxInt.compareTo(snum) >= 0 && minInt.compareTo(snum) <= 0)
{
num = Integer.parseInt(snum);
}
if(negval == true)
{
num = num * -1;
}
value = num;
return value;
}
}
You are comparing Strings which don't work the same way as comparing numbers. For example, "10" < "2" because '1' < '2' and this means that "-1" < "-2147483648" and "3" > "2147483647"
It's difficult to suggest what you should do instead as it's not clear to me why you are doing half of the code you have e.g. Can you say how your code is different from
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
return 0;
}
Your main problem is that you're using a string comparison to compare numbers. Also, since you already know that the number is positive, there's not much point comparing it to minInt. Lastly, you have the wrong value for maxInt.
Simply use Integer.parseInt(snum)
final String maxInt = "2147483648";
MAX_INT is 2147483647.
Second of all, do not use String comparison to compare numbers. Use it like this:
if (Integer.parseInt(maxInt) >= Integer.parseInt(snum)) {
num = Integer.parseInt(snum);
}

Categories

Resources