Convert Hexadecimal number to decimal in Java (Android) - java

As in the title above. I want take the hex number from an EditText
EditText number = (EditText) findViewById (R.id.etDisplay);
Editable stringEditable = number.getText().toString;
String nuovo = stringEditable.toString();
I want to convert nuovo to a decimal number.

int i = Integer.parseInt(nuovo, 16);

int i = Integer.parseInt(nuovo,16);

The accepted answer will work in some cases, but if your number may be bigger than Integer.MAX_VALUE, you may want to use something like this:
public static long hexToLong(String hex) {
return Long.parseLong(hex, 16);
}

Try Integer.parseInt(nuovo,16).

Here's a small demo for you. It uses the java.util.Scanner and coverts it.
import java.util.Scanner;
public class hex {
static long dec=0;
static long squ(int i)
{
long pow=16;
if(i==0)
{
return 1;
}
else if(i==1)
{
return pow;
}
else
{
for(int k=2;k<=i;k++)
{
pow=pow*16;
}
return pow;
}
}
public static void main(String[] args) {
Scanner so=new Scanner(System.in);
System.out.println("enter the hexa decimal no");
String hx=so.next();
hx.toLowerCase();
char c[]=hx.toCharArray();
int j=c.length;
int x=j;
int i=0;
j--;
while(j>=0)
{
if(c[j]=='a'|c[j]=='b'|c[j]=='c'|c[j]=='d'|c[j]=='e'|c[j]=='f'|c[j]=='1'|c[j]=='2'|c[j]=='3'|c[j]=='4'|c[j]=='5'|c[j]=='6'|c[j]=='7'|c[j]=='8'|c[j]=='9')
{
j--;
}
else
{
i++;
break;
}
}
if(i>0)
{
System.out.println("its not hex decimal no");
}
else
{
System.out.println("it s hex decimal no");
x--;
int xy=0;
while(x>=0)
{
long z=squ(xy);
++xy;
char r=c[x];
String s=""+r;
switch(s)
{
case "a": dec=dec+(10*z);
break;
case "b": dec=dec+(11*z);
break;
case "c": dec=dec+(12*z);
break;
case "d": dec=dec+(13*z);
break;
case "e": dec=dec+(14*z);
break;
case "f": dec=dec+(15*z);
break;
case "1": dec=dec+(1*z);
break;
case "2": dec=dec+(2*z);
break;
case "3": dec=dec+(3*z);
break;
case "4": dec=dec+(4*z);
break;
case "5": dec=dec+(5*z);
break;
case "6": dec=dec+(6*z);
break;
case "7": dec=dec+(7*z);
break;
case "8": dec=dec+(8*z);
break;
case "9": dec=dec+(9*z);
break;
case "0": dec=dec+(0*z);
break;
default:System.out.println("cant find****"+s);
break;
}
x--;
}
System.out.println("final decimal equ is*****"+dec);
}
}
}

Related

Taking int input and parsing into char

So my main got deleted 2 days ago and my teacher helped me a bit with the switch code. I rebuilt the code yesterday and he was away yesterday and could not help me.
public static void main(String[] args) throws InterruptedException {
do {
try {
System.out.println("Enter your birthYear");
birthYear = Integer.parseInt(input.next());
int length = String.valueOf(birthYear).length();
System.out.println(length);
if (length != 4) {
lengthTest = false;
System.out.println("Invalid Choice");
} else {
lengthTest = true;
}
test = true;
} catch (Exception e) {
System.out.println("Invalid Choice");
}
} while (test == true ^ lengthTest != false);
do {
System.out.println("Please enter a number between 1-4 \n"
+ "1 = AreaOfTriangle \n" +
"----------------------------------\n" +
"2 = HoursToDaysAndHours Calculator \n" +
"---------------------------------- \n" +
"3 = CelciusToFahrenheit Calculator \n" +
"----------------------------------\n" +
"4 = BirthdayGame \r\n" +
"----------------------------------");
try {
choice = Integer.toString(input.nextInt()).charAt(0);
System.out.println(choice);
switch (choice) {
case 1:
aOT.areaOfTriangle();
break;
case 2:
hTDAH.hoursToDaysAndHours();
break;
case 3:
cTF.celciusToFahrenheit();
case 4:
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}
}catch (Exception e) {
System.out.println("Invalid Awnser");
}
} while (repeat == true);
}
My problem is in my switch case i want to be able to use int's and Char's at the same time. For example i want to use e to exit and and the 4 numbers
You can try to use String as an input paramenter, then any int value or char will be readed correctly without necessity to convert them:
try {
String choice = input.next();
System.out.println(choice);
switch (choice) {
case "1":
aOT.areaOfTriangle();
break;
case "2":
hTDAH.hoursToDaysAndHours();
break;
case "3":
cTF.celciusToFahrenheit();
case "4":
System.out.println("Code not implemented");
break;
case "e":
repeat = false;
break;
default:
System.out.println("");
break;
}
You can't use int and chars at the same time, as you can only use one variable and a variable has to have a type, but:
If you cast a char or Character to int you get values. For example ((int) 'e') evaluates to 101 if I am not mistaken. (Try System.out.println((int) 'e'));
So in your case, you can switch over int values and detect for 1,2,3,4 and 101.
Your default should also throw an exception and you are fine.
Happy Coding
You could just use the char representations of the digits 1-4:
char choice = input.next().charAt(0);
switch (choice) {
case '1':
aOT.areaOfTriangle();
break;
case '2':
hTDAH.hoursToDaysAndHours();
break;
case '3':
cTF.celciusToFahrenheit();
case '4':
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}

Checking if a String is a number using switch

I have to make a program which tells if a String that I type in my keyboard is a number, by using a switch. I know how to do it with try and catch, but I don't know how to do it with switch.
Any tips?
You would need to check each characer in the String. Something like this would probably work.
static boolean isNumber(String s) {
if (s == null) {
// Debatable.
return false;
}
int decimalCount = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// These are all allowed.
break;
case '.':
if (i == 0 || decimalCount > 0) {
// Only allow one decimal in the number and not at the start.
return false;
}
decimalCount += 1;
break;
default:
// Everything else not allowed.
return false;
}
}
return true;
}
Up to Java7 you can use switch(String) statement.
But here you have enough with switch(int) and a little workaround:
public static void main(String[] args) throws Exception {
String a = "2";
switch (Integer.parseInt(a)) {
default:
System.out.print("is a number");
break;
}
}
This is the solution I got asking to some classmates and thinking it quietly.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner entry = new Scanner(System.in);
String myNumber;
int tf;
myNumber = entry.next();
try {
Double.parseDouble(myNumber);
tf = 1;
}
catch (Exception e) {
tf = 0;
}
switch(tf) {
case 1:
System.out.println("Is a number");
break;
default:
System.out.println("No es un nĂºmero");
break;
}
}
Thanks to the community for being so nice!
I came up with a shorter code BUT it uses regular expressions, which if Halo is just starting with Java, he may have not seen that topic yet. But then it answers the question too so here it is:
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
String matches = new Boolean(expression.matches("\\d+")).toString();
switch (matches) {
case "true":
System.out.println("IT'S a number");
break;
case "false":
System.out.println("NOT a number");
}
scanner.close();

could use some help on this decode(char c) method

The program is to write a calss PhoneNumber.java
I understand that I am supposed to test if the string is a digit or a letter and then if it is a letter its supposed to be decoded by decode(char c);
However, I dont think char c should be in between the ( ) If any one has suggestions thatd be great thanks!! The toString is left unreturned intentionally because i have not gotten that far in the program yet. Also, have to keep it in the case 'A' format Thanks
public class PhoneNumber {
private int areacode;
private int number;
private int ext;
PhoneNumber() {
areacode = 0;
number = 0;
ext = 0;
}
PhoneNumber(int newnumber) {
areacode = 216;
number = newnumber;
ext = 0;
}
PhoneNumber(int newarea, int newnumber, int newext) {
areacode = newarea;
number = newnumber;
ext = newext;
}
PhoneNumber(String newnumber) {
String areacode = str[0];
String number = str[1];
String[] str = newnumber.split("-");
String[] number = newnumber;
boolean b1, b2;
int i = 0;
int place = 0;
for (int x: newnumber){
newnumber.charAt[i] = place;
b1 = Character.isDigit(place);
if (b1 == true){
number = place;
i++;
} else {
b2 = Character.isLetter(place);
} if (b2 == true) {
number = decode(place);
i++;
} else {
System.out.print("invalid phone number!");
}
}
System.out.print(areacode.concat(number));
return newnumber;
}
private String decode(place) {
switch (c) {
case 'A': case 'B': case 'C': return "2";
case 'D': case 'E': case 'F': return "3";
case 'G': case 'H': case 'I': return "4";
case 'J': case 'K': case 'L': return "5";
case 'M': case 'N': case 'O': return "6";
case 'P': case 'Q': case 'R': case 'S': return "7";
case 'T': case 'U': case 'V': return "8";
case 'W': case 'X': case 'Y': case 'z': return "9";
default: return "";
}
}
public boolean equals(PhoneNumber pn) {
}
public String toString() {
}
}
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:53: error: <identifier> expected
private String decode(place) {
^
1 error
In the constructor, you need to declare the array before you put things in it. You also can't say String[] number = newnumber because number is a String[] and newnumber is a String. equals() and toString() need to return something. And, to answer your question, just say
private String decode(char c){

Switch ignore case in java 7

I am doing a POC on Java 7 new features. I have code to use String in switch statement and it works. I want to make it work in case insensitive also. Is there a way to check out with ignoreCase on String?
package com.java.j7;
public class Test {
final private String _NEW ="NEW";
final private String _PENDING = "PENDING";
final private String _CLOSED = "CLOSED";
final private String _REJECTED ="REJECTED";
public static void main(String... strings){
Test j = new Test();
j.processItem("new");
j.processItem("pending");
j.processItem("closed");
j.processItem("rejected");
}
void processItem(String s){
switch (s) {
case _NEW:
System.out.println("Matched to new");
break;
case _PENDING:
System.out.println("Matched to pending");
break;
case _CLOSED:
System.out.println("Matched to closed");
break;
case _REJECTED:
System.out.println("Matched to rejected");
break;
default:
System.out.println("Not matching any more");
break;
}
}
}
no, but you could switch on s.toUpperCase(). so:
switch (s.toUpperCase()) {
//same as before
}
and while we're nitpicking, you better upper-case things in the english locale to avoid issues with turkish
using String in switch Example from oracle docs Using Strings in switch Statements
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
From oracle docs switch with string
The String in the switch expression is compared with the expressions associated with each case label as if the String#equals method were being used.
You can use
switch(s.toUpperCase()){
...
.....
}
See also
String#toUpperCase

Need assignment idea

I need help with my assignment.I need to write class program that tranlates grade into grade point. If the grade have + like A+ it will increase the grade point by 0.3 and - will decrease by 0.3.
private static final double GradePoint = 0;
private static Scanner input;
public static void main(String [] args)
{
String grade ;
double GradePoint = 0;
System.out.print("Please enter your grade: ");
input = new Scanner(System.in);
grade = input.nextLine();
switch(grade)
{
case "A":
case "a": GradePoint = 4; break;
case "B":
case "b": GradePoint = 3; break;
case "C":
case "c": GradePoint = 2; break;
case "D":
case "d": GradePoint = 1; break;
case "F":
case "f": GradePoint = 0; break;
}
System.out.print("Your grade is: "+GradePoint);
}
public double getGradePoint(String grade)
{
return GradePoint;
}
What i dont understand is about how to use the method to calculate.I'm still beginner.
I have to use CLASS and method*public double getGradePoint(String grade)* to
return the grade point of grade entered.
You need to shift your entire code from main() to getGradePoint(String grade);
also your switch case switch(grade) will not work for values like "A+" as there are no such case that matches the string "A+"
I was bored and had nothing better to do so here :)
public class GradeCalculator
{
public static void main(String[] args)
{
System.out.print("Please enter your grade: ");
Scanner input = new Scanner(System.in);
String grade = input.nextLine().trim();
GradeCalculator calculator = new GradeCalculator();
double gradePoint = calculator.getGradePoint(grade);
System.out.print("Your grade is: " + gradePoint);
}
private double getGradePoint(String grade)
{
int score = getGradeScore(grade.charAt(0));
double modifier = 0;
if (grade.length() > 1)
{
modifier = getModifierValue(grade.charAt(1));
}
return score + modifier;
}
private int getGradeScore(char grade)
{
int score = 0;
switch (grade)
{
case 'A':
case 'a':
score = 4;
break;
case 'B':
case 'b':
score = 3;
break;
case 'C':
case 'c':
score = 2;
break;
case 'D':
case 'd':
score = 1;
break;
case 'F':
case 'f':
score = 0;
break;
}
return score;
}
private double getModifierValue(char modifier)
{
double value = 0;
switch (modifier)
{
case '+':
value = 0.3;
break;
case '-':
value = -0.3;
break;
}
return value;
}
}

Categories

Resources