I'm taking a computer organization class in college. I was tasked with writing a java program that takes a user-inputted string, calls a function that converts said string into a hexadecimal integer, and then outputs the results.
The kicker is that I can't use any existing syntax to do this. for example, Integer.parseInt(__,16) or printf. It all neds to be hardcoded.
Now I'm not asking you to do my homework for me, just wanting to be put in the right direction.
So far, I've made this but can't seem to get the method created right:
import java.util.*;
public class Demo_Class
{
public static void main(String[] args)
{
Scanner AI = new Scanner(System.in);
String str;
System.out.println("Please input a hexadecimal number: ");
str = AI.nextLine();
converter(str);
}
public static int converter(String in)
{
String New = new String();
for(int i = 0; i<= in.length(); i++)
{
New += in.charAt(i);
System.out.println(New + 316);
}
return 0;
}
}
Consider this, lets says you have the hex value 1EC which in hex digits would be 1, E, C. In decimal they would be 1, 14, 12.
so set sum = 0.
sum = sum*16 + 1. sum is now 1
sum = sum*16 + 14 sum is now 30
sum = sum*16 + 12 sum is now 492
So 492 is the answer.
If you have a string of 1EC you need to convert to characters and then convert those characters to the decimal equivalent of hex values.
Try this on paper until you get the feel and then code it. You can check your results using the Integer method you mentioned.
#WJS gave a good hint, I'd just like to add that the charAt() returns the char, which is encoded in ASCII.
As you can see in the ASCII table, the characters A-F have decimal values from 65 to 70, while 0-9 go from 48 to 57 so you'll need to use them to convert the ASCII characters to their intended value.
To do so, you can either get the decimal value of a character by casting to short like short dec = (short)in.charAt(i);, or directly use the characters like char current = in.charAt(i) - 'A'.
With this in mind, all that's left is some calculation, I'll leave that as the homework. :)
Also:
you are looping one character more than needed, change the i <= in.length() to i < in.length(), since it's going from 0
I don't know what that 316 "magic number" is, if it does mean something, declare a variable with a meaningful name, like:
final int MEANINGFUL_NAME = 316;
Related
I am working on the problem to find the next greatest number with the same set of digits.
For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.
But when I take
int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. How can I overcome this ?
it is not possible in java to take the int values with leading zeros.
so for the value with leading zeros take it in string format.
but we can insert zeros
int n=7;
String str=String.format("%04d", n); //4 denotes the size of the string
System.out.println(str); // o/p->0007
It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int.
int is not capable of storing trailing zeros.
Take this sample.
int foo = Integer.valueOf("09");
System.out.println(foo);
Output
9
So to solve your problem you should get a String from the user, validate it and parse it to an Integer[].
Solution
public Integer[] parseToInteger(String number) {
return Arrays.asList(number.toCharArray())
.stream()
.map(c -> Integer.valueOf(c.toString()))
.toArray(size -> new Integer[size]);
}
Now you have an Array of Integer.
Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.
If I want to convert 9 to '9' I usually just add '0' to it.
You can also do the following:
char c = Character.forDigit(9,10);
If you have a string of characters, you can do the following:
String str = "09";
List<Character> chrs =
str.chars().mapToObj(a -> Character.valueOf((char) a))
.collect(Collectors.toList());
System.out.println(chrs);
Prints
[0,9]
You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve. So let's take one step backward, and lets make sure I understand your problem correctly.
You say that you have to find the "next greatest number with the same set of digits". So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number. For example, given the input "09", you would output "90", and for "123", you would output "132". Is that right? Let assume so.
Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number. Actually, there's a few possible strategies:
Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value. That would be a very innefficient strategy, requiring both disproportionate memory and processing power. Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).
Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values. That one might look simple to implement, but it actually hides some complexities (i.e. determining that two numbers are composed from the same digits is not trivial, special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits). Anyway, this strategy would also be rather innefficient, requiring considerable processing power.
Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number. This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first. The algorithm is O(n log n), where n is the length of the number (in digits). Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it. This is definitely the way to go.
All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself. In the last strategy, you actually never need the actual value itself. You are simply playing Scrabble, with digits rather than letters.
So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):
public static void main(String[] args) {
// Read input number and parse it into an array of digit
String inputText = readLineFromUser();
int[] inputDigits = parseToDigits(inputText);
// Determine the next greater number
int[] outputDigits = findNextGreaterNumber(inputDigits);
// Output the resulting value
String outputText = joinDigits(outputDigits);
println(outputText);
}
So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough). So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input. This can be written in various ways in Java, but I think the most simple would be with a simple for loop:
public static int[] parseToDigits(String input) {
char[] chars = input.toCharArray();
int[] digits = new int[chars.length];
for (int i = 0 ; i < chars.length ; i++)
digits[i] = Character.forDigit(chars[i], 10);
return digits;
}
Note that Character.forDigit(digit, radix) returns the value of character digit in base radix; if digit is not valid for the given base, forDigit returns 0. For simplicity, I'm skipping proper validation checking here. One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.
As to the opposite opperation, joinDigits, it would looks like:
public static String joinDigits(int[] digits) {
char[] chars = new char[digits.length];
for (int i = 0 ; i < digits.length ; i++)
chars[i] = Character.digit(digits[i], 10);
return new String(chars);
}
Hope that helps.
I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}
I was given an assignment to generate a random number between 1 to 26 then convert that number to a letter from 'a' to 'z'.
the random generating part looks fine but when I try to cast the number to char, I would just get an empty square-like box!
why is that?
import java.util.Random;
public class NumbersToLetters
{
public static void main(String[] args)
{
Random n;
int num;
n=new Random();
//generating a random number from 1 to 26
num=Math.abs(((n.nextInt())%26)+1);
//cast from int to char
char myChar = (char) num;
System.out.println ("Number - " + num);
System.out.println ("Char - " + myChar);
//I'm sure that my answer is right but no matter what I do,
//it won't output a letter, all I get is a square-like box..
}
}
You're generating a number between 1 and 27 (inclusive). If you look at what those characters correspond to, you'll see that none of them are actually printable.
You should do your calculation as + 'a' instead of + 1
n.nextInt(26) + 'a';
This will give you the correct offset (which happens to be 97) to find the lower case letters.
The character 'a' is not encoded as 1, but as 97. You need to add 'a' to a value between 0 and 25 (inclusive) to get the expected result:
num = 'a'+n.nextInt(26);
I'm not a Java guru like others on here, but it might have something to do with not being encoded correctly? Look up UTF-8 encoding and just research type casting
I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());
I have a program that I am working on which would effectively convert binary, decimal, or hex numbers to other formats (don't ask why I'm doing this, I honestly don't know). So far I only have a binary - decimal conversion going, and it works fine however whenever the binary number entered is 8 digits or more it crashes.
As far as I can tell when I input the number 10011001 it gets translated to scientific notation and becomes 1.0011001E7 which wouldn't really be a problem, except that the way I am converting the numbers involves creating a string with the same value as the number and breaking it into individual characters. Unfortunately, this means I have a string valued "1.0011001E7" instead of "10011001", so when I cut up the characters I hit the "." and the program doesn't know what to do when I try to make calculations with that. So basically my question comes down to this, how do I force it to use the not-scientific notation version for these calculations?
Thanks for all your help, and here is the code if it helps at all:
//This Splits A Single String Of Digits Into An Array Of Individual Digits
public float[] splitDigits(float fltInput){
//This Declares The Variables
String strInput = "" + fltInput;
float[] digit = new float[strInput.length() - 2];
int m = 0;
//This Declares The Array To Hold The Answer
for (m = 0; m < (strInput.length() - 2); m++){
digit[m] = Float.parseFloat(strInput.substring(m, m + 1)); //Breaks here
}
//This Returns The Answer
return digit;
}
Just use BigDecimal
BigDecimal num = new BigDecimal(fltInput);
String numWithNoExponents = num.toPlainString();
Note here the fltInput will be automatically converted to a double.