I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.
public static void main(String[] args) {
System.out.print("Enter a roman numeral: ");
Scanner in = new Scanner(System.in);
String Roman = in.next();
int largo = Roman.length();
char Roman2[] = new char[largo];
int Roman3[] = new int[largo];
for (int i = 0; i < largo; i++) {
Roman2[i] = Roman.charAt(i);
}
for (int i = 0; i < largo; i++) {
if (Roman2[i] == 'I') {
Roman3[i] = 1;
} else if (Roman2[i] == 'V') {
Roman3[i] = 5;
} else if (Roman2[i] == 'X') {
Roman3[i] = 10;
} else if (Roman2[i] == 'L') {
Roman3[i] = 50;
} else if (Roman2[i] == 'C') {
Roman3[i] = 100;
} else if (Roman2[i] == 'M') {
Roman3[i] = 1000;
}
}
int total = 0;
for (int m = 0; m < Roman3.length; m++) {
total += Roman3[m];
}
System.out.println("The Roman is equal to " + total);
}
You can check the previous digit.
For example, I added the condition that detects IV :
if (Roman2[i]=='I'){
Roman3[i]=1;
} else if (Roman2[i]=='V'){
Roman3[i]=5;
if (i>0 && Roman2[i-1]=='I') { // check for IV
Roman3[i]=4;
Roman3[i-1]=0;
}
} else if (Roman2[i]=='X'){
Roman3[i]=10;
} else if (Roman2[i]=='L'){
Roman3[i]=50;
} else if (Roman2[i]=='C'){
Roman3[i]=100;
} else if (Roman2[i]=='M'){
Roman3[i]=1000;
}
Define enum like below:
public enum RomanSymbol {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private RomanSymbol(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
if (lastArabicNumber > this.value) {
return totalArabicResult - this.value;
} else {
return totalArabicResult + this.value;
}
}
}
And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.
So if you accept character from user, you can get the values as:
char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();
And if you have string like IV, then you could calculate on something like for example:
int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on
Related
Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.
I have this method:
public static int parseInt(String str) {
if (isValidNumber(str)) {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
return -1;
}
which converts a string into a integer. And as you can see it is (at the moment) in a if-statement with a method which checks if the input is a valid input for my purpose:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9'){
return true;
}
}
return false;
}
I want the string to be number only (negative and positive) no other is allowed. At that time a string i.e 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. I think you guys understand what I mean. I don't know how to do that.
Please help!
Try this:
CODE:
public class validNumbers {
public static void main(String[] args) {
System.out.println(parseInt("345"));
System.out.println(parseInt("-345"));
System.out.println(parseInt("a-345"));
System.out.println(parseInt("1a5b"));
}
public static int parseInt(String str) {
String numberWithoutSign = removeSign(str);
if (isValidNumber(numberWithoutSign)) {
int sum = 0;
int position = 1;
for (int i = numberWithoutSign.length() - 1; i >= 0; i--) {
int number = numberWithoutSign.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
if(isNegative(str)){
return -(sum);
}else{
return sum;
}
}
return -1;
}
/**
* Removes sign in number if exists
*/
public static String removeSign(String number){
if(number.charAt(0) == '+' || number.charAt(0) == '-'){
return number.substring(1);
}else{
return number;
}
}
/**
* Determines if a number is valid
*/
public static boolean isValidNumber(String number) {
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if(c >= '0' && c <= '9'){
continue;
}else{
return false;
}
}
return true;
}
/**
* Determines if a number is negative or not
*/
public static boolean isNegative(String number){
if(number.charAt(0) == '-'){
return true;
}else{
return false;
}
}
}
OUTPUT:
345
-345
-1
-1
To check if a string is a real number you can use a method like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
The problem is with your function isValidNumber. It should return a false on first occurrence of a non numeric value, as follows:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(!(c >= '0' && c <= '9')){
if (i > 0) {
return false;
}
//This will only be invoked when `i == 0` (or less, which is impossible in this for loop), so I don't need to explicitly specify it here, as I have checked for `i > 0` in the above code...
if (c != '-' && c != '+') {
return false;
}
}
}
return true;
}
This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}
The problem i have is that only the decryption does not give me correct result. The code is running perfect in encryption but in decryption it return a wrong result.
I do not know what is the problem, only the decryption it does not work. Could someone please help me?
//main
public static void main(String[] args) {
int key[]=new int[26];
int ikey[]=new int[26];
String EncMsg =JOptionPane.showInputDialog(null, "enter plain text ");
String plaintext = (EncMsg).replaceAll("\\s","").toLowerCase();
for(int h=0;h<key.length;h++){
String MsgKey=JOptionPane.showInputDialog(null,"enter random keys");
key[h]= Integer.parseInt(MsgKey);
}
//total means collect all letters in one sentence
String total="";
for (int i = 0; i < plaintext.length(); i++) {
char ch = plaintext.charAt(i);
int letterNumber = convertLetter2Number(ch);
int enc = key[letterNumber];
total += convertNumber2Letter(enc);
}
// generating inverted key array
for (int i=0; i<26; i++)
{
for (int j =0; j<26; j++)
{
if(j== key[i])
{
ikey[j] = i ;
break;
}}
}
String total2="";
for (int i = 0; i < total.length(); i++) {
char result = total.charAt(i);
int letterNumber = convertLetter2Number(result);
int dec= ikey[letterNumber];
total2 += convertNumber2Letter(dec);
}
JOptionPane.showMessageDialog(null,"Encryption message : "+total);
JOptionPane.showMessageDialog(null,"Decryption message : "+total2);
}
//convert number to letters ( it has to be random )
public static char convertNumber2Letter(int key){
char[] letters = new char[26];
letters[0]='b';
letters[1]='a';
letters[2]='d';
letters[3]='c';
letters[4]='f';
letters[5]='e';
letters[6]='h';
letters[7]='g';
letters[8]='j';
letters[9]='i';
letters[10]='l';
letters[11]='k';
letters[12]='n';
letters[13]='m';
letters[14]='p';
letters[15]='o';
letters[16]='r';
letters[17]='q';
letters[18]='t';
letters[19]='s';
letters[20]='v';
letters[21]='u';
letters[22]='x';
letters[23]='w';
letters[24]='z';
letters[25]='y';
return letters[key];
}
// convert letter to number ( arranged )
public static int convertLetter2Number(char ltr){
if(ltr=='a'){
return 0;
}else if(ltr=='b'){
return 1;
}else if(ltr=='c'){
return 2;
}else if(ltr=='d'){
return 3;
}else if(ltr=='e'){
return 4;
}else if(ltr=='f'){
return 5;
}else if(ltr=='g'){
return 6;
}else if(ltr=='h'){
return 7;
}else if(ltr=='i'){
return 8;
}else if(ltr=='j'){
return 9;
}else if(ltr=='k'){
return 10;
}else if(ltr=='l'){
return 11;
}else if(ltr=='m'){
return 12;
}else if(ltr=='n'){
return 13;
}else if(ltr=='o'){
return 14;
}else if(ltr=='p'){
return 15;
}else if(ltr=='q'){
return 16;
}else if(ltr=='r'){
return 17;
}else if(ltr=='s'){
return 18;
}else if(ltr=='t'){
return 19;
}else if(ltr=='u'){
return 20;
}else if(ltr=='v'){
return 21;
}else if(ltr=='w'){
return 22;
}else if(ltr=='x'){
return 23;
}else if(ltr=='y'){
return 24;
}else if(ltr=='z'){
return 25;
}
else {
return -1;
}
}}
//end
Herro, Um I'm not sure if this is how you use this site but uh lets get to it... So I need help on this project and I have to do this -
Input [][] Output
A - F -> Multiply by 3, Divide by 4
G - J -> Divide by 3 + 25
K - N -> Find Greatest Factor * 2
O - Q -> Find largest prime inclusive * 3
R - W -> Find Smallest Factor Except 1
X - Z -> Sum Numbers
So I was wondering if my first couple is correct, and need help on the empty space. So the Letter represents the number of the as in "Z" is the last letter so its 26, and "A" is the first so its 1. So if an responses... Thanks ! package Fun;
import java.util.Scanner;
public class Fun {
public static void main(String[] args) {
// TODO Auto-generated method stub
run();
}
public static void run()
{
input();
evaluateAlphabet();
evaluate();
}
public static void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Letter, please");
x = sc.next();
}
public static String x = " ";
public static int temp = 0;
public static int answer = 0;
public static void evaluateAlphabet()
{
if(x.equals("A"))
{
temp = 1;
}
else if (x.equals("B"))
{
temp = 2;
}
else if (x.equals("C"))
{
temp = 3;
}
else if (x.equals("D"))
{
temp = 4;
}
else if (x.equals("E"))
{
temp = 5;
}
else if (x.equals("F"))
{
temp = 6;
}
else if (x.equals("G"))
{
temp = 7;
}
else if (x.equals("H"))
{
temp = 8;
}
else if (x.equals("I"))
{
temp = 9;
}
else if (x.equals("J"))
{
temp = 10;
}
else if (x.equals("K"))
{
temp = 11;
}
else if (x.equals("L"))
{
temp = 12;
}
else if (x.equals("M"))
{
temp = 13;
}
else if (x.equals("N"))
{
temp = 14;
}
else if (x.equals("O"))
{
temp = 15;
}
else if (x.equals("P"))
{
temp = 16;
}
else if (x.equals("Q"))
{
temp = 17;
}
else if (x.equals("R"))
{
temp = 18;
}
else if (x.equals("S"))
{
temp = 19;
}
else if (x.equals("T"))
{
temp = 20;
}
else if (x.equals("U"))
{
temp = 21;
}
else if (x.equals("V"))
{
temp = 22;
}
else if (x.equals("W"))
{
temp = 23;
}
else if (x.equals("X"))
{
temp = 24;
}
else if (x.equals("Y"))
{
temp = 25;
}
else if (x.equals("Z"))
{
temp = 26;
}
else if (x.equals("Qwerty"))
{
temp = 27;
}
}
public static void evaluate()
{
if(temp>=1 && temp<= 6)
{
answer = (temp * 3)/4;
System.out.println("Answer is " + answer);
}
else if(temp >= 7 && temp<= 10)
{
answer = (temp/3) + 25;
System.out.println("Answer is " + answer);
}
else if(temp >= 11 && temp<= 14)
{
}
else if(temp>=15 && temp<= 17)
{
for(int i = temp; i>0; i--)
{
for(int j = 2; j <=i/2 + 1; j++)
{
if(i%j==0)
{
break;
}
if(j==i/2 + 1)
{
answer = i * 3;
}
}
}
System.out.println("Answer is " + answer);
}
else if(temp>=18 && temp<= 23)
{
answer = temp;
}
else if(temp>= 24 && temp<=26)
answer = (answer * 12)%26;
System.out.println("Answer is " + answer);
}
}
-Corruption
Here is a better approach for char to int conversion:
Assuming the string has at least 1 character(check for its length), you can get the temp by doing:
temp = x.getCharAt(0) - 'A' + 1;
or, safety first:
temp = 0;
if (x.matches("^[A-Z]{1}$") {
temp = x.getCharAt(0) - 'A' + 1;
}
What's happening here? Every character has an ASCII code, an integer. So, when you have 2 chars and you try to get the distance between them, the result is an int. 'A' - 'A' = 0(that's why i added a + 1), 'B' - 'A' = 1 and so on.
For the if condition, I am using a RegExp. ^ means start of the input, [A-Z]{1} means one of A-Z, $ means the end of the input. So, if it's an A-Z, temp will get a value, anything else won't make it in the if and your temp will remain 0 so you can easily test if you've got an A-Z or not.
That's all for code review, I won't give you solutions, you must work harder, use Google. You won't enjoy and learn if I give you everything ready for a copy paste.