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 8 years ago.
Improve this question
I have to write a Java program to convert Arabic numerals into Roman and vice versa, but I have troubles with my code,can anybody show me on this example how it should realy look,because i have got no idea how it shoud look like(
import java.util.*;
public class Du3 {
static int last = 2000;
static int numbers[] = {1, 4, 5, 9, 10, 50, 100, 500, 1000 };
static String letters[] = { "I", "IV", "V", "IX", "X", "L", "C", "D", "M"};
public static void main (String[] args){
System.out.println("Enter your Roman Numerals or Integer number:");
Scanner cti = new Scanner(System.in);
String a = cti.next();
char c = a.charAt( 0 );
char a1=convertRomanToInt(romanValue);
if ( Character.isDigit( c ) ){
System.out.println("Roman value = " + integerValue);}
else {
System.out.println("Integer value = " + romanValue);
}
static int convertRomanToInt(String romanNumeral){
int integerValue = 0;
for (int i = 0; i < romanNumeral.length(); i++){
char ch = romanNumeral.charAt( i );
int number = letterToNumber( ch );
if ( number == -1){
throw new NumberFormatException("Invalid format");
}
if (last<number)
number-=last- 1;
integerValue += number;
last = number;
}
return integerValue;
}
private static int letterToNumber(char letter){
switch (letter) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
static String convertIntegerToRoman(int number){
String romanValue = "";
int N = number;
while ( N > 0 ){
for (int i = 0; i < numbers.length; i++){
if ( N < numbers[i] ){
N -= numbers[i-1];
romanValue += letters[i-1];
break;
}
}
}
return romanValue;
}
}
Well, this is clearly wrong:
char a1=convertRomanToInt(romanValue);
The method convertRomanToInt() returns an int but you are assigning it to a1, which is a char.
Then you never do anything with a1, but you go on to try and print the variable integerValue:
if ( Character.isDigit( c ) ){
System.out.println("Roman value = " + integerValue);}
But integerValue is only declared inside the scope of the convertRomanToInt() method. It's not available in main().
Related
as the title suggests I am writing a simple prog using methods, that converts the char input of a Roman Numeral between ("M", "D", "C", "L", "X", "V", "I") And then printing the decimal equivalent.
I have written the program but it converts the decimal (int) to Roman Numeral
When modifying the program to accepts char input only to ("M", "D", "C", "L", "X", "V", "I") then outputting decimal, I get errors since char cannot be converted to int.
Any suggestions on how I would change this. Thanks
import java.util.Scanner;
class RomanNumeral {
public static String romanNumeralToInt(int romanNumeral) {
String Numeral = "";
int repeat;
int value[] = {1000, 500, 100, 50, 10, 5, 1 };
String symbol[] = {"M", "D", "C", "L", "X", "V", "I" };
for(int x = 0; romanNumeral > 0; x++) {
repeat = romanNumeral / value[x];
for(int i = 1; i <= repeat; i++) {
Numeral = Numeral + symbol[x];
}
romanNumeral = romanNumeral % value[x];
}
return Numeral;
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
final String INVALID = "Invalid number, try again!";
final int VALIDATE_NUMBER_1 = 1;
final int VALIDATE_NUMBER_5 = 5;
final int VALIDATE_NUMBER_10 = 10;
final int VALIDATE_NUMBER_50 = 50;
final int VALIDATE_NUMBER_100 = 100;
final int VALIDATE_NUMBER_500 = 500;
final int VALIDATE_NUMBER_1000 = 1000;
while (true) {
System.out.print("Enter a number: ");
int inputValue = input.nextInt();
if (inputValue == VALIDATE_NUMBER_1) {
System.out.println(VALIDATE_NUMBER_1 + " = " + romanNumeralToInt(1));
}
else if (inputValue == VALIDATE_NUMBER_5) {
System.out.println(VALIDATE_NUMBER_5 + " = " + romanNumeralToInt(5));
}
else if (inputValue == VALIDATE_NUMBER_10) {
System.out.println(VALIDATE_NUMBER_10 + " = " + romanNumeralToInt(10));
}
else if (inputValue == VALIDATE_NUMBER_50) {
System.out.println(VALIDATE_NUMBER_50 + " = " + romanNumeralToInt(50));
}
else if (inputValue == VALIDATE_NUMBER_100) {
System.out.println(VALIDATE_NUMBER_100 + " = " + romanNumeralToInt(100));
}
else if (inputValue == VALIDATE_NUMBER_500) {
System.out.println(VALIDATE_NUMBER_500 + " = " + romanNumeralToInt(500));
}
else if (inputValue == VALIDATE_NUMBER_1000) {
System.out.println(VALIDATE_NUMBER_1000 + " = " + romanNumeralToInt(1000));
}
else {
System.out.println(INVALID);
}
}
}
}
UPDATE
Code modified as suggested from post, althought still has errors as String cannot be converted to Int. Any suggestions. Thank you
import java.util.Scanner;
class RomanTest {
public static int romanNumeralToInt(char romanNumeral) {
String Numeral = "";
int repeat;
int value[] = {1000, 500, 100, 50, 10, 5, 1 };
char symbol[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I' };
for(char x = 0; romanNumeral > 0; x++) {
repeat = romanNumeral / value[x];
for(int i = 1; i <= repeat; i++) {
Numeral = Numeral + symbol[x];
}
romanNumeral = romanNumeral % value[x];
}
return Numeral;
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
final String INVALID = "Invalid number, try again!";
final char VALIDATE_CHAR_M = 'M';
final char VALIDATE_CHAR_D = 'D';
final char VALIDATE_CHAR_C = 'C';
final char VALIDATE_CHAR_L = 'L';
final char VALIDATE_CHAR_X = 'X';
final char VALIDATE_CHAR_V = 'V';
final char VALIDATE_CHAR_I = 'I';
while (true) {
System.out.print("Enter a number: ");
char inputValue = input.nextLine().charAt(0);
if (inputValue == VALIDATE_CHAR_M) {
System.out.println(VALIDATE_CHAR_M + " = " + romanNumeralToInt('M'));
}
else if (inputValue == VALIDATE_CHAR_D) {
System.out.println(VALIDATE_CHAR_D + " = " + romanNumeralToInt('D'));
}
else if (inputValue == VALIDATE_CHAR_C) {
System.out.println(VALIDATE_CHAR_C + " = " + romanNumeralToInt('C'));
}
else if (inputValue == VALIDATE_CHAR_L) {
System.out.println(VALIDATE_CHAR_L + " = " + romanNumeralToInt('L'));
}
else if (inputValue == VALIDATE_CHAR_X) {
System.out.println(VALIDATE_CHAR_X + " = " + romanNumeralToInt('X'));
}
else if (inputValue == VALIDATE_CHAR_V) {
System.out.println(VALIDATE_CHAR_V + " = " + romanNumeralToInt('V'));
}
else if (inputValue == VALIDATE_CHAR_I) {
System.out.println(VALIDATE_CHAR_I + " = " + romanNumeralToInt('I'));
}
else {
System.out.println(INVALID);
}
}
}
}
First of all you should pay attention public static int romanNumeralToInt(char romanNumeral) it should return int, but you are returning String Numeral = ""; - it's String, Java as C# is strongly typed language, so you have to return String.
Second: concatenating String in way you are doing
for(int i = 1; i <= repeat; i++) {
Numeral = Numeral + symbol[x];
}
is not recommended (too slow, String is immutable so on every concatenation you are creating new String). Better approach is to use StringBuilder.
I've modified your code and came with something like :
private String decimalToRoman(int number) {
String[] romans = {"M", "CM", "D", "C", "XC", "L", "X", "IX", "V", "I"};
int[] values = {1000, 900, 500, 100, 90, 50, 10, 9, 5, 1};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.length; i++) {
int times= number / values[i];
if (times== 0) {
continue;
}
if (times == 4 && i > 0) {
builder.append(romans[i]);
builder.append(romans[i - 1]);
} else {
for (int ii = 0; ii < times; ii ++) {
builder.append(romans[i]);
}
}
number = number % values[i];
}
return builder.toString();
}
You are doing very things in the wrong way. Here is one way to do.
class RomanNumeral {
public static void romanNumeralToInt(String romanNumeral) {
Map<Character,Integer> mapping = new HashMap<>();
mapping.put('M',1000);
mapping.put('D',500);
mapping.put('C',100);
mapping.put('L',50);
mapping.put('X',10);
mapping.put('V',5);
mapping.put('I',1);
int result = 0;
for(char each : romanNumeral.toCharArray()){
if(mapping.containsKey(each)){
result += mapping.get(each);
}
else{
System.out.println("Invalid number");
return;
}
}
System.out.println(result);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
String inputValue = input.nextLine();
romanNumeralToInt(inputValue);
}
}
The code in the main method already just accept the values 1000, 500, 100, 50, 10, 5, 1. Then in your romanNumeralToInt, there is some operations which are not necessary. Because you already have two arrays mapping for example 1 to I or 5 to V. If you find the index of 1 in the int array then your roman numeral is symbol[foundIndex]. I did not get the the purpose of those two for loops.
I get errors since char cannot be converted to int.
char can be converted to int. But "M" is not char, it is a String. 'M' is a char.
You can get a char from the user in the following way:
char charValue = input.nextLine().charAt(0);
Thanks for the help guys. Looked into arrays. Think I have it, but I'm having a hard time with getting it to print out. Any ideas? It prints out the word test, but only after several spaces (assuming thats where my letters are supposed to show up) Came up with this:
import java.util.Scanner;
public class q1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] aArray = new char[10];
String[] Acypher = { "D", "D", "W", "E", "L", "H", "O", "R" };
for (int i = 0; i < 10; ++i) {
int input = in.nextInt();
switch (input) {
case 1:
String newin1 = Acypher[1];
break;
case 2:
String newin2 = Acypher[2];
break;
case 3:
String newin3 = Acypher[3];
break;
case 4:
String newin4 = Acypher[4];
break;
case 5:
String newin5 = Acypher[5];
break;
case 6:
String newin6 = Acypher[6];
break;
case 7:
String newin7 = Acypher[7];
break;
default:
System.out.println("Translation unknown. Please enter a new number.");
--i;
break;
}
}
String aArrayDc = new String(aArray);
System.out.println(aArrayDc + "test");
}
}
This is a possible solution, but next time do your homework without asking for the solution
import java.util.Scanner;
public class q1 {
public static void main(String[] args) {
char[] cipher = { 'D', 'W', 'E', 'L', 'H', 'O', 'R' };
char decoded[] = new char[10];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 10; ++i) {
int num;
do {
num = in.nextInt();
} while (num < 1 || num > 7);
decoded[i] = cipher[num - 1];
}
System.out.println(decoded);
}
}
You'll probably want to rewrite your iterations to a for loop.
for(int i = 0; i < 10; ++i)
{
int input = in.nextInt();
//switch statement
}
You need to use a switch statement to find the letter for each number, we add a default case to handle an incorrect number.
This switch goes in the for loop.
switch(input)
{
case 1:
//store letter to array
break;
...
default:
--i;
System.out.println("Incorrect number, please enter a new number");
}
To store the letter of each match, we create an array, we already know it needs a length of 10.
This line goes before the for loop:
char[] decodedCharacters = new char[10]
Put this one in each switch statement:
decodedCharacters[i] = "D"; //another letter for each case.
And this one is to print all characters:
String decodedString = new String(decodedCharacters);
System.out.println(decodedString);
EDIT:
See #Guillaume 's answer for an approach leaving more flexibility for other combinations.
His answer doesn't handle an incorrect number though.
This is probably a simple error that I am over looking but my problem is that when I am trying to return the string "roman", it just returns null.
This is the main program:
/* CCTPG-22 // Assignment 08: Roman Numerals
* #author Kevin R. Trujillo
* #version 10/28/2015
* Purpose: Converts numbers into roman numerals format and vice-a-versa
* Status:
*/
import java.util.*; // For Scanner
public class RomanMain
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
RomanYear year1 = new RomanYear(1975);
RomanYear year2 = new RomanYear(1988);
RomanYear year3 = new RomanYear(2007);
System.out.println(year1.toString());
System.out.println(year2.toString());
System.out.println(year3.toString());
int diff21 = year2.getYearDecimal() - year1.getYearDecimal();
int diff32 = year3.getYearDecimal() - year2.getYearDecimal();
RomanYear y2MinusY1 = new RomanYear(diff21);
RomanYear y3MinusY2 = new RomanYear(diff32);
System.out.println("Year2 minus Year1 is: " + y2MinusY1.getYearRoman());
System.out.println("Year3 minus Year2 is: " + y3MinusY2.getYearRoman());
}
// Add new methods here
} // No code can be here (outside the class)
and here is the RomanYear class:
/**
* Auto Generated Java Class.
*/
public class RomanYear {
private int decimal ;
private String roman ;
public RomanYear() // default constructor
{
decimal = 0 ;
roman = "" ;
}
public RomanYear(int newYear)
{
decimal = newYear ;
roman = setYearDecimal(decimal);
}
public RomanYear(String newYear )
{
roman = newYear ;
decimal = setYearRoman(roman) ;
}
public int setYearRoman(String roman)
{
String romanNumeral = roman.toUpperCase();
for(int x = 0;x < romanNumeral.length(); x++)
{
char convertToDecimal = roman.charAt(x);
// first step: Easy stuff
switch (convertToDecimal)
{
case 'M': decimal += 1000; break;
case 'D': decimal += 500; break;
case 'C': decimal += 100; break;
case 'L': decimal += 50; break;
case 'X': decimal += 10; break;
case 'V': decimal += 5; break;
case 'I': decimal += 1; break;
}
}
// Now adapt for specials
if (romanNumeral.contains("IV"))
{
decimal-=2;
}
if (romanNumeral.contains("IX"))
{
decimal-=2;
}
if (romanNumeral.contains("XL"))
{
decimal-=20;
}
if (romanNumeral.contains("XC"))
{
decimal-=20;
}
if (romanNumeral.contains("CD"))
{
decimal-=200;
}
if (romanNumeral.contains("CM"))
{
decimal-=200;
}
return decimal ;
}
public String setYearDecimal(int yr)
{
if (decimal > 3999)
{
System.out.println("Decimal Number: " + decimal + " is over 3999. ") ;
System.out.println("Please enter a new number") ;
System.out.println("Program is ending.............") ;
try {
Thread.sleep(2000); //5000 milliseconds is one second.
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.exit(0) ;
}
else
{
int digit;
String roman = "";
// 1000's column
digit = yr/1000;
for (int i = 0; i < digit; i++)
roman = roman + "M";
yr = yr % 1000; // leaves 0 to 999
// 100s column
String [] hunds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
digit = yr/100;
roman = roman + hunds[digit];
yr = yr % 100; // leaves 0 to 99
// 10s column
String [] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
digit = yr/10;
roman = roman + tens[digit];
yr = yr % 10; // leaves 0 to 9
// Ones column
String [] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
roman = roman + ones[yr];
}
return roman ;
}
public int getYearDecimal()
{
return decimal ;
}
public String getYearRoman()
{
return roman ;
}
public String toString()
{
System.out.print("Decimal: " + decimal + " as Roman Numerals is " ) ;
return roman ;
}
/* ADD YOUR CODE HERE */
}
If someone could just explain what I am doing wrong, that would be much appreciated rather than just posting the "correct way" to do it.
Thank you!
On the top of the Roman class you create a variable called roman.
public class RomanYear {
private int decimal ;
private String roman ;
In setYearDecimal you create a new variable called roman. That local variable hides the global one.
int digit;
String roman = "";
When you do roman = roman + "M"; you are only updating the local roman variable. The global one remains empty.
All you need to do is remove String from in front of the second variable.
Here I have created a flames game logic it is final string length is correct(eg:4 for two strings 'raja' and 'rani') based on length I need to show 'f' or 'l' or 'a' or 'm' or 'e' or 's'.
I have written logic based on length that character is visible but that is not my concern. For length 4 result should be 'e'(in flames for length 4 first 'm' should remove then 'l' then 'f' then 'a' then 's' finally i need 'e' as output.Can anybody tell me idea. This is my code.
public static void main(String[] args) {
String name1 = "raja";
String name2 = "rani";
String s1 = name1;
String s2 = name2;
for (int i = 0; i < name1.length(); i++) {
for (int j = 0; j < name2.length(); j++) {
if (name1.charAt(i) == name2.charAt(j)) {
name1 = name1.replaceFirst(String.valueOf(name1.charAt(i)), "#");
name2 = name2.replaceFirst(String.valueOf(name2.charAt(j)), "#");
}
}
}
String result = name1 + name2;
result = result.replaceAll("#", "");
int resultLength = result.length();
String baseInput = "flames";
char relationIs = 0;
int temp = 0;
if (resultLength > 0) {
temp = resultLength % baseInput.length();
}
if (temp == 0 && resultLength >= 6) {
relationIs = 's';
} else {
int count = temp - 1;
if (count >= 0) {
relationIs = baseInput.charAt(count);
System.out.println("Relation Betw " + s1 + " and " + s2 + " is:");
}
}
switch (relationIs) {
case 'f':
System.out.println("friendship");
break;
case 'l':
System.out.println("Lovers");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemity");
break;
case 's':
System.out.println("Siblings");
break;
default:
System.out.println("FLAME Test works only for different names");
break;
}
}
Logic follows this order:only forward direction remove 4 character.
if length=4
step 0:flames ('f' as 1)
step 1:flaes (here 'e' as 1)
step 2:faes (here 'a' as 1)
step 3:aes (here 'a' as 1)
step 4:es (here 'e' as 1)
step 5:e //output.
Your help will be appreciated.
Hope this is what you need. I am here striking the character of the word flames until i am getting one character. Once i get the character that is what the result of flames.
if (resultLength > 0) {
while (baseInput.length() !=1)
{
System.out.println(baseInput);
int tmpLen = resultLength % baseInput.length(); //finding char position to strike
if(tmpLen != 0)
{
temp = baseInput.substring(tmpLen) + baseInput.substring(0, tmpLen-1); //Append part start from next char to strike and first charater to char before strike.
}
else
{
temp = baseInput.substring(0, baseInput.length()-1); //If mod result zero we can strike last letter easily
}
baseInput = temp; //Assign the temp to baseinput for next iteration.
}
relationIs = baseInput.charAt(0);
System.out.println(relationIs);
}
Link : http://ideone.com/Fqgcc1
I think the problem is with this line:
int count = temp - 1;
Which is giving you an answer of 3 which gives (0)F (1)L (2)A (3)M
So change it to:
int count = temp; //- 1;
To get (0)F (1)L (2)A (3)M (4)E
// Another Right Code to Find FLAMES in JAVA
// It is simple
import java.util.Scanner;
class Flames
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
String name,fname,flm="flames";
System.out.println("Enter the boy name...");
name=sc.next();
System.out.println("Enter the girl name...");
fname=sc.next();
int l=name.length();
int gl=fname.length();
int num=0,tl=0;
char n[]=name.toCharArray();
char gn[]=fname.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<gl;j++)
{
if(n[i]==gn[j])
{
n[i]='*';
gn[j]='*';
break;
}
}
}
String tname=new String(n);
tname=tname+(new String(gn));
tname=tname.replace("*","");
tl=tname.length();
System.out.println(tl);
for(int s=6;s>=2;s--)
{
if(tl>s)
num=tl-s;
else
num=tl;
while(num>s)
{
num=num-s;
}
flm=flm.substring(num,flm.length())+(flm.substring(0,num-1));
}
switch(flm.charAt(0))
{
case 'f': System.out.println("Relationship = Friends"); break;
case 'l': System.out.println("Relationship = Lovers"); break;
case 'a': System.out.println("Relationship = Affections"); break;
case 'm': System.out.println("Relationship = Married"); break;
case 'e': System.out.println("Relationship = Enemy"); break;
case 's': System.out.println("Relationship = Brother & Sisters"); break;
}
//System.out.println("Name ="+flm);
}
}
import java.util.Scanner;
public class Flames {
public static void main(String[] args) {
/* Check the flames using two names */
Scanner scan = new Scanner(System.in);
System.out.print("Enter Name 1 : ");
String Name1 = scan.nextLine();
//System.out.println(Name1);
System.out.print("Enter Name 2 : ");
String Name2 = scan.nextLine();
//System.out.println(Name2);
int N1len = Name1.length();
int N2len = Name2.length();
Name1 = Name1.toLowerCase();
Name2 = Name2.toLowerCase();
StringBuffer NameB1 = new StringBuffer(Name1);
StringBuffer NameB2 = new StringBuffer(Name2);
int Name3=0;
for (int i = 0; i<N1len; i++)
{
for (int j = 0; j<N2len; j++)
{
if (NameB1.charAt(i) == NameB2.charAt(j))
{
NameB1 = NameB1.deleteCharAt(i);
NameB2 = NameB2.deleteCharAt(j);
N1len= NameB1.length();
N2len= NameB2.length();
i=0;
j=0;
}
}
}
Name3= NameB1.length()+NameB2.length();
//System.out.println(NameB1);
//System.out.println(NameB2);
//System.out.println(Name3);
/* Flames Calculation */
char flameResult =0;
String flames = "flames";
StringBuffer sb3 = new StringBuffer(flames);
while (sb3.length()!=1)
{
int Name4 = Name3%sb3.length();
String temp;
if(Name4!=0)
{
temp = sb3.substring(Name4)+sb3.substring(0, Name4-1);
}
else
{
temp=sb3.substring(0,sb3.length()-1);
}
sb3 = new StringBuffer(temp);
flameResult=sb3.charAt(0);
}
switch(flameResult)
{
case 'f': System.out.println("Friends");
break;
case 'l':
System.out.println("Love");
break;
case 'a':
System.out.println("Affection");
break;
case 'm':
System.out.println("Marriage");
break;
case 'e':
System.out.println("Enemies");
break;
case 's':
System.out.println("Sibling");
break;
}
}
}
import java.util.*;
public class Flames
{
public static void main()
{
int sp=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter two names");
String s=sc.nextLine().toLowerCase();
String s1=sc.nextLine().toLowerCase();
String p="flames";
String p1="flames";
String s2="";
String m="";
for(int i=0;i < s.length();i++)
{
if(Character.isLetter(s.charAt(i)))
{
m=m+s.charAt(i);
}
}
s=m;
m="";
for(int i=0;i < s1.length();i++)
{
if(Character.isLetter(s1.charAt(i)))
{
m=m+s1.charAt(i);
}
}
s1=m;
m="";
int l=s.length();
int l1=s1.length();
for(int i=0;i < l;i++)
{
int sl=0;
for(int j=0;j < s1.length();j++)
{
if(s.charAt(i)==s1.charAt(j))
{
if(sl==0)
{
sl++;sp++;s2=s2+" " ;
}
else
{
s2=s2+s1.charAt(j);
}
}
else
{
s2=s2+s1.charAt(j);
}
}
s1=s2;
s2="";
}
sp=sp*2;
int c=(l-1)+(l1-1)-(sp-1);
for(int i=1;;i++)
{
String z="";p=p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p+p;
String mn="";
char c1=p.charAt(c);
for(int j=0;j < p1.length();j++)
{
if(c1==p1.charAt(j))
{
mn=p1.substring(j+1)+mn;
break;
}
else
{
mn=mn+p1.charAt(j);
}
}
for(int k=0;k < p1.length();k++)
{
if(c1==p1.charAt(k))
{
}
else
{
z=z+p1.charAt(k);
}
}
p1=z;
p=mn;
if(mn.length()==1)
{
System.out.println(mn);
break;
}
}
}
}
i am trying to implement a java method which accepts an input in RPN (Reverse Polish Notation) and through use of a stack converts it into an infix notation and calculates it. I have built the stack and a working converter but i am finding problems when it comes to accepting multiple digit numbers (such as 10), my idea to solve this was to enter each separate entity separated by a space, 10+20 would be entered as "10 20 +" but this is resulting in an out of bounds error. Without the section marked below the program works fine for equations such as "12+" (1+2) and more complex ones as long as they involve single digit values. The stack is fully functiopnal too with push and pop methods
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("Enter an equation: ");
String eq = sc.nextLine();
int len = eq.length();
for (int i = 0; i < len; i++){
String car1 = String.valueOf(eq.charAt(i));
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
This bit does not work
while (len < i+1 && eq.charAt(i+1) != ' '){
car1 = car1+eq.charAt(i+1);
i++;
}
Till here
myStack.push(car1);
}
}
mainMenu();
}
This was fixed using the split method in the string class as so
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.print("Enter an equation: ");
System.out.println();
String eq = sc.nextLine();
//This Bit splits up the string where it meets a space
String[] eqS = eq.split(" ");
int len = eqS.length;
for (int i = 0; i < len; i++){
String car1 = eqS[i];
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
myStack.push(car1);
}
}
mainMenu();
}