Hex to decimal conversion from a bufferreader - java

I am having a lot of trouble getting my code to read a certain file, which has 4 hex codes, using buffer reader and converting it to decimal. I was able to get the bufferreader to read the text file and output it to the compiler but i need the program to store the 4 values and have my method convert hex to decimal. This is what i have so far:
import java.io.BufferedReader;
import static java.lang.System.*;
import java.io.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class HexToDecimal {
public static int hexToDecimal(String hexInput) throws IOException {
int decimal = 0;
int len = hexInput.length();
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
out.printf(line + "\n");
}
in.close();
for (int i = 0; i < len; ++i) {
char c = hexInput.charAt(i);
int cValue;
switch (c) {
case '1':
cValue = 1;
break;
case '2':
cValue = 2;
break;
case '3':
cValue = 3;
break;
case '4':
cValue = 4;
break;
case '5':
cValue = 5;
break;
case '6':
cValue = 6;
break;
case '7':
cValue = 7;
break;
case '8':
cValue = 8;
break;
case '9':
cValue = 9;
break;
case 'A':
cValue = 10;
break;
case 'B':
cValue = 11;
break;
case 'C':
cValue = 12;
break;
case 'D':
cValue = 13;
break;
case 'E':
cValue = 14;
break;
case 'F':
cValue = 15;
break;
default: // unexpected character
throw new IllegalArgumentException("Non-hex character " + c
+ " found at position " + i);
}
decimal = 16 * decimal + cValue;
}
return decimal;
}
public static void main(String[] args) {
}
}
Also i can't use parseInt that's why i'm using case breaks. Which is also giving me trouble when it comes to converting hex to decimal. Any help at all is greatly appreciated.

You could change your code in that way and it will work:
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
public class HexToDecimal {
public static BigInteger hexToDecimal(String hexInput) throws IOException {
BigInteger decimal = BigInteger.ZERO;
int len = hexInput.length();
for (int i = len - 1; i >= 0; i--) {
char c = hexInput.charAt(len - i - 1);
BigInteger cValue;
switch (c) {
case '1':
cValue = BigInteger.ONE;
break;
case '2':
cValue = BigInteger.valueOf(2l);
break;
case '3':
cValue = BigInteger.valueOf(3l);
break;
case '4':
cValue = BigInteger.valueOf(4l);
break;
case '5':
cValue = BigInteger.valueOf(5l);
break;
case '6':
cValue = BigInteger.valueOf(6l);
break;
case '7':
cValue = BigInteger.valueOf(7l);
break;
case '8':
cValue = BigInteger.valueOf(8l);
break;
case '9':
cValue = BigInteger.valueOf(9l);
break;
case 'A':
cValue = BigInteger.valueOf(10l);
break;
case 'B':
cValue = BigInteger.valueOf(11l);
break;
case 'C':
cValue = BigInteger.valueOf(12l);
break;
case 'D':
cValue = BigInteger.valueOf(13l);
break;
case 'E':
cValue = BigInteger.valueOf(14l);
break;
case 'F':
cValue = BigInteger.valueOf(15l);
break;
default: // unexpected character
throw new IllegalArgumentException("Non-hex character " + c
+ " found at position " + i);
}
decimal = decimal.add(cValue
.multiply(BigInteger.valueOf(16).pow(i)));
}
return decimal;
}
public static void main(String[] args) throws IOException {
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
String[] hexNums = line.split(" ");
for (String hex : hexNums)
out.printf(hexToDecimal(hex) + "\n");
}
in.close();
}
}
If you have to big numbers then you get a wrong answer with int as type so you have to use BigInteger and then the code looks like above with reading from file and printing to the output stream.
I hope it helps.

As Leonid Glanz said just convert the hex String to decimal with Integer.parseInt(hexString, 16). To store more than one value just use a ArrayList.
Edit: Sry didn't read your Op correctly
Here is a bit of code you can use:
import java.io.BufferedReader;
import static java.lang.System.*;
import java.io.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class HexToDecimal {
public static ArrayList<Integer> hexToDecimal() throws IOException {
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
String ram = "";
ArrayList<String> lines = new ArrayList<>();
ArrayList<Integer> output = new ArrayList<>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
for(String y : lines){
ram = "";
for(char x : y.toCharArray()){
ram += convert(x);
}
output.add(Integer.parseInt(ram));
}
in.close();
return output;
}
public static int convert(char x){
if(x == '1'){
return 1;
}else if(x == '2'){
return 2;
}else if(x == '3'){
return 3;
}else if(x == '4'){
return 4;
}else if(x == '5'){
return 5;
}else if(x == '6'){
return 6;
}else if(x == '7'){
return 7;
}else if(x == '8'){
return 8;
}else if(x == '9'){
return 9;
}else if(x == 'A'){
return 10;
}else if(x == 'B'){
return 11;
}else if(x == 'C'){
return 12;
}else if(x == 'D'){
return 13;
}else if(x == 'E'){
return 14;
}else if(x == 'F'){
return 15;
}else{
return 0;
}
}
public static void main(String[] args) {
try {
System.out.println(hexToDecimal());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

calculating sin, cos, log using stack and post fix notation in java

I wanna write a program that that take a infix string and change it to postfix then evaluate postfix and print the answer ; for +-*/^ it's easy just need precedence of operators but I don't know what should I do for sin cos log and other math function.
private static String infixToPostfix(String infix) {
String[] exp = infix.split("");
Stack<String> stack = new Stack<>();
String result = "";
for (int i = 0; i < exp.length; i++){
if (exp[i].equals("(")) {
stack.push(exp[i]);
}
else if (isOperator(exp[i]))
{
while (!stack.isEmpty() && precedence(exp[i]) <= precedence(stack.getTop())){
result += stack.pop() + " ";
}
stack.push(exp[i]);
}
else if (exp[i].equals(")"))
{
while (!stack.isEmpty() && !stack.getTop().equals("(")){
result += stack.pop() + " ";
}
stack.pop();
}
else if (Character.isLetterOrDigit(infix.charAt(i)) || exp[i].equals(".")){
boolean haveDot = exp[i].equals(".");
String temp = haveDot ? "0." : exp[i];
while ((i + 1) < exp.length && (Character.isLetterOrDigit(infix.charAt(i + 1)) || exp[i + 1].equals("."))){
temp += exp[i + 1];
i++;
}
result += temp + " ";
}
}
while (!stack.isEmpty()){
result += stack.pop() + " ";
}
return result;
}
it is working correctley !
but this
private static Double postFixEvaluator(String[] postFix) {
Stack<Double> operands = new Stack<>();
double value = 0.0;
for (int str = 0; str < postFix.length; str++) {
if (postFix[str].trim().equals("")) {
continue;
}
switch (postFix[str]) {
case "+":
case "-":
case "*":
case "/":
case "^":
Double right = operands.pop();
Double left = operands.pop();
long intValue = 0;
switch (postFix[str]) {
case "+":
value = left + right;
break;
case "-":
value = left - right;
break;
case "*":
value = left * right;
break;
case "/":
value = left / right;
break;
case "^":
value = Math.pow(left, right);
break;
default:
break;
}
case "sin":
case "cos":
case "tan":
case "cot":
if (Character.isLetterOrDigit(Arrays.toString(postFix).charAt(str + 2))) {
str++;
break;
}
else{
Double oper = operands.pop();
switch (postFix[str]) {
case "sin":
value = Math.sin(oper);
break;
case "cos":
value = Math.cos(oper);
break;
case "tan":
value = Math.tan(oper);
break;
case "cot":
value = 1 / Math.tan(oper);
break;
}
}
operands.push(value);
break;
default:
operands.push(Double.parseDouble(postFix[str]));
break;
}
}
return operands.pop();
}
it's not working correctly .

Constant Expression Required When Using an Array With a Switch Statement

Hello StackOverflow community, I've just begun to work with arrays and I was wondering how I can make the switch statement work with the values below. It's really irritating that it won't work considering the only error is constant expression required:
import java.lang.Character;
public class Ass11a {
public static char[] vowel = new char[4];
public static char[] consonant = new char[20];
public static char[] number = new char[9];
public static char[] punctuation = new char[10];
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter a character: ");
char input = console.readChar();
Character.toLowerCase(input);
vowel[0] = 'a';
vowel[1] = 'e';
vowel[2] = 'i';
vowel[3] = 'o';
vowel[4] = 'u';
consonant[0] = 'q';
consonant[1] = 'w';
consonant[2] = 'r';
consonant[3] = 't';
consonant[4] = 'y';
consonant[5] = 'p';
consonant[6] = 's';
consonant[7] = 'd';
consonant[8] = 'f';
consonant[9] = 'g';
consonant[10] = 'h';
consonant[11] = 'j';
consonant[12] = 'k';
consonant[13] = 'l';
consonant[14] = 'z';
consonant[15] = 'x';
consonant[16] = 'c';
consonant[17] = 'v';
consonant[18] = 'b';
consonant[19] = 'n';
consonant[20] = 'm';
number[0] = '1';
number[1] = '2';
number[2] = '3';
number[3] = '4';
number[4] = '5';
number[5] = '6';
number[6] = '7';
number[7] = '8';
number[8] = '9';
number[9] = '0';
punctuation[0] = '.';
punctuation[1] = ',';
punctuation[2] = '?';
punctuation[3] = '!';
punctuation[4] = ';';
punctuation[5] = ':';
punctuation[6] = '"';
punctuation[7] = '\'';
punctuation[8] = '(';
punctuation[9] = ')';
punctuation[10] = '-';
switch(input)
{
case vowel[0]:case vowel[1]:case vowel[2]:case vowel[3]:case vowel[4]:
System.out.println("Vowel");
break;
case consonant[0]:case consonant[1]:case consonant[2]:case consonant[3]:
case consonant[4]:case consonant[5]:case consonant[6]:case consonant[7]:
case consonant[8]:case consonant[9]:case consonant[10]:case consonant[11]:
case consonant[12]:case consonant[13]:case consonant[14]:case consonant[15]:
case consonant[16]:case consonant[17]:case consonant[18]:case consonant[19]:
case consonant[20]:
System.out.println("Consonant");
break;
case number[0]:case number[1]:case number[2]:case number[3]:case number[4]:
case number[5]:case number[6]:case number[7]:case number[8]:case number[9]:
System.out.println("Number");
break;
case punctuation[0]:case punctuation[1]:case punctuation[2]:case punctuation[3]:
case punctuation[4]:case punctuation[5]:case punctuation[6]:case punctuation[7]:
case punctuation[8]:case punctuation[9]:case punctuation[10]:
System.out.println("Punctuation");
break;
default:
System.out.println("Other");
break;
}
}
}
You could use an enum like this
public enum Vowels {
A,E,I,O,U;
static boolean isVowel(char c) {
switch (c) {
case 'A': case 'a':
case 'E': case 'e':
case 'I': case 'i':
case 'O': case 'o':
case 'U': case 'u': return true;
}
return false;
}
static Vowels getVowel(char c) {
switch (c) {
case 'A': case 'a': return A;
case 'E': case 'e': return E;
case 'I': case 'i': return I;
case 'O': case 'o': return O;
case 'U': case 'u': return U;
}
return null;
}
}
and use it like
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
while (console.hasNextLine()) {
String input = console.nextLine();
for (Character ch : input.toCharArray()) {
if (Vowels.isVowel(ch)) {
System.out.println(ch + " is vowel");
}
}
}
}

Convert Decimal to Hex using Recursive method Java

I need to make a recursive method that converts a decimal into hexadecimal.
I can't use Integer.toHexString.
EDIT:I tried this code but it doesn't work properly
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return Integer.toString(0);
} else {
switch (remainder) {
case 10:
result = "A" + result;
break;
case 11:
result = "B" + result;
break;
case 12:
result = "C" + result;
break;
case 13:
result = "D" + result;
break;
case 14:
result = "E" + result;
break;
case 15:
result = "F" + result;
break;
default: result = Integer.toString(n/16) + result; break;
}
System.out.println(result);
return Hexa(Integer.toString(n/16)) + result;
}
}
Edit:
Changed the default case and the if (n == 0) loop return statement and it works beautifully now.
new code:
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return "";
} else {
switch (remainder) {
case 10:
result = "A";
break;
case 11:
result = "B";
break;
case 12:
result = "C";
break;
case 13:
result = "D";
break;
case 14:
result = "E";
break;
case 15:
result = "F";
break;
default:
result = remainder + result;
break;
}
return Hexa(Integer.toString(n / 16)) + result;
}
}
The problem is in your default clause:
default: result = Integer.toString(n/16) + result; break;
it should read:
default: result = Integer.toString(remainder) + result; break;
That will make your program return "04D2".
But there are several other corrections you can make:
Stop converting back and forth to String. For example that same line can be just:
default: result = remainder + result; break;
Also, change your parameters time to int. If you do need to receive a String, then make this an auxiliary function and make your main function receive a String.
You don't need that breakat the end of your default
You don't need a switch. Isn't 'F' = 'A' + (15 - 10) ? You can figure out how to make a formula that translates any number in the range [10,15] to its corresponding letter.
Instead of Integer.toString(0) you can use "0" ... but that isn't even necessary, you can use "" to avoid that leading 0 in your output. If your are worried for handling the special case where the whole number is "0" add a special clause.
The code below may help you to solve your problem:
public static String decimalToAnyBase(int num,int base) {
if(num<base) {
return num+"";
}
String result=null;
int rem=num%base;
String str=decimalToAnyBase(num/base, base);
result=str+((rem>=10)? (char)(rem-10+'A')+"":rem);
return result;
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Ques5 {
public static void hex(int n) {
if(n>9&&n<=15) {
System.out.printf("%c",'A'+(n-10));
}
else if(n>=0&&n<=9){
System.out.printf("%d",n);
}
else {
hex(n/16);
hex(n%16);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the decimal number : ");
int i = sc.nextInt();
System.out.println("The hexadecimal number is : ");
hex(i);
sc.close();
}
}
const char hex_string[17] = "0123456789ABCDEF";
void dec_to_hex(long long x){
if(x == 0) return;
dec_to_hex(x/16);
printf("%c",hex_string[x%16]);
}
Same in Java

Is there a more efficient way to do this? | Month conversion

I was given a little task to complete where a user would be asked to input either a month or the numerical equivalent and it would return the numerical value of the entered month, or the month corresponding to the inputted numerical value. The constraints are as follows:
- It must not contain a GUI of any kind
- I have to use the BufferedReader for input
- I have to use at least one Switch statement
If anyone has any ideas, it would be greatly appreciated.
My code so far is as follows:
/**
* Month task
*
* #author Dan Foad
* #version 0.01
*/
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Months {
public static void main(String []args) throws IOException {
int iInput;
boolean isParseable;
String szInput;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please type either the number of the month, or the month itself to convert.");
System.out.print("> ");
szInput = br.readLine();
try {
Integer.valueOf(szInput);
isParseable = true;
}
catch(Exception e) {
isParseable = false;
}
if (isParseable) {
iInput = Integer.valueOf(szInput);
System.out.println(numberToMonth(iInput));
}
else {
szInput = szInput.toLowerCase();
System.out.println(monthToNumber(szInput));
}
return;
}
public static String numberToMonth(int iMonth) {
String MonthReturn;
switch(iMonth) {
case (1): MonthReturn = "January"; break;
case (2): MonthReturn = "February"; break;
case (3): MonthReturn = "March"; break;
case (4): MonthReturn = "April"; break;
case (5): MonthReturn = "May"; break;
case (6): MonthReturn = "June"; break;
case (7): MonthReturn = "July"; break;
case (8): MonthReturn = "August"; break;
case (9): MonthReturn = "September"; break;
case (10): MonthReturn = "October"; break;
case (11): MonthReturn = "November"; break;
case (12): MonthReturn = "December"; break;
default: MonthReturn = "0"; break;
}
return MonthReturn;
}
public static int monthToNumber(String szMonth) {
int MonthReturn;
switch(szMonth) {
case ("january"): MonthReturn = 1; break;
case ("february"): MonthReturn = 2; break;
case ("march"): MonthReturn = 3; break;
case ("april"): MonthReturn = 4; break;
case ("may"): MonthReturn = 5; break;
case ("june"): MonthReturn = 6; break;
case ("july"): MonthReturn = 7; break;
case ("august"): MonthReturn = 8; break;
case ("september"): MonthReturn = 9; break;
case ("october"): MonthReturn = 10; break;
case ("november"): MonthReturn = 11; break;
case ("december"): MonthReturn = 12; break;
default: MonthReturn = 0; break;
}
return MonthReturn;
}
}
How about this?
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
import static java.util.Calendar.APRIL;
import static java.util.Calendar.AUGUST;
import static java.util.Calendar.DECEMBER;
import static java.util.Calendar.FEBRUARY;
import static java.util.Calendar.JANUARY;
import static java.util.Calendar.JULY;
import static java.util.Calendar.JUNE;
import static java.util.Calendar.MARCH;
import static java.util.Calendar.MAY;
import static java.util.Calendar.NOVEMBER;
import static java.util.Calendar.OCTOBER;
import static java.util.Calendar.SEPTEMBER;
public class Months {
public static void main(String []args) throws IOException {
Integer iInput = null;
String szInput = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please type either the number of the month, or the month itself to convert.");
System.out.print("> ");
szInput = br.readLine();
boolean wasInt = false;
try {
iInput = Integer.valueOf(szInput);
System.out.println(numberToMonth(iInput));
wasInt = true;
}
catch(Exception e) {
}
if (! wasInt) {
szInput = szInput.toLowerCase();
System.out.println(monthToNumber(szInput));
}
return;
}
public static String numberToMonth(int iMonth) {
switch(iMonth-1) {
case (JANUARY): return "January";
case (FEBRUARY): return "February";
case (MARCH): return "March";
case (APRIL): return "April";
case (MAY): return "May";
case (JUNE): return "June";
case (JULY): return "July";
case (AUGUST): return "August";
case (SEPTEMBER): return "September";
case (OCTOBER): return "October";
case (NOVEMBER): return "November";
case (DECEMBER): return "December";
}
return "Unknown";
}
public static int monthToNumber(String szMonth) {
if (szMonth == null) {
return 0;
}
switch(szMonth.toLowerCase()) {
case ("january"): return 1 + JANUARY;
case ("february"): return 1 + FEBRUARY;
case ("march"): return 1 + MARCH;
case ("april"): return 1 + APRIL;
case ("may"): return 1 + MAY;
case ("june"): return 1 + JUNE;
case ("july"): return 1 + JULY;
case ("august"): return 1 + AUGUST;
case ("september"): return 1 + SEPTEMBER;
case ("october"): return 1 + OCTOBER;
case ("november"): return 1 + NOVEMBER;
case ("december"): return 1 + DECEMBER;
}
return 0;
}
}
You can also do this:
private static final String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
public static String numberToMonth(int iMonth) {
return (iMonth < 12 && iMonth > 0) ? monthNames[iMonth - 1] : "None";
}
You can add the strings "1","2","3", ..., "12" to your monthToNumber method, that way you won't have to convert the user input to Integer using String.valueOf.
Yeah in the number to month method you can just create a String array with the names of the months in chronological order and then just fetch the string at the index of the given input value minus 1

StringIndexOutOfBoundsException while decoding

I am using ISO9075 decoder in my application. When I try to decode the following String
ISO9075.decode("mediaasset_-g9mdob83oozsr5n_xadda")
its giving the following exception
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 22
at java.lang.String.charAt(Unknown Source)
at org.alfresco.util.ISO9075.matchesEncodedPattern(ISO9075.java:128)
at org.alfresco.util.ISO9075.decode(ISO9075.java:176)
at Test1.main(Test1.java:9)
What may be the problem. Please guide me.
EDIT
Here is my code
public class Test1 {
public static void main(String args[])
{
String s = "mediaasset_-g9mdob83oozsr5n_xadda";
System.out.println(ISO9075.decode(s));
}
}
Thanks.
I just tested it with code found here and could not get your exception.
public static void main(String args[]) {
String s = "mediaasset_-g9mdob83oozsr5n_xadda";
System.out.println(ISO9075.decode(s)); //prints mediaasset_-g9mdob83oozsr5n_xadda
}
public static class ISO9075 {
//I have removed the parts not used by your main()
private static boolean matchesEncodedPattern(String string, int position) {
return (string.length() > position + 6)
&& (string.charAt(position) == '_') && (string.charAt(position + 1) == 'x')
&& isHexChar(string.charAt(position + 2)) && isHexChar(string.charAt(position + 3))
&& isHexChar(string.charAt(position + 4)) && isHexChar(string.charAt(position + 5))
&& (string.charAt(position + 6) == '_');
}
private static boolean isHexChar(char c) {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return true;
default:
return false;
}
}
public static String decode(String toDecode) {
if ((toDecode == null) || (toDecode.length() < 7) || (toDecode.indexOf("_x") < 0)) {
return toDecode;
}
StringBuffer decoded = new StringBuffer();
for (int i = 0, l = toDecode.length(); i < l; i++) {
if (matchesEncodedPattern(toDecode, i)) {
decoded.append(((char) Integer.parseInt(toDecode.substring(i + 2, i + 6), 16)));
i += 6;// then one added for the loop to mkae the length of 7
} else {
decoded.append(toDecode.charAt(i));
}
}
return decoded.toString();
}
}

Categories