I am trying to get the last two and first two digits from a number. I am getting a really weird result with the return value of my lastTwo function.
public static int lastTwo(int digit){
String str = Integer.toString(digit);
String lastTwo = str.substring(str.length()-2);
int response = Integer.parseInt(lastTwo);
return response;
}
When the input digit is 104, the output of this is just 4, but when the input is 114, the output is 14 which is the correct output. Why is substring on 104 not returning a 0 in the correct place?
here is my bluej console just for extra visuals:
twoDigit.main({ }) (104)
4
10
twoDigit.main({ }) (114)
14
10
Your code is doing the splitting correctly, but primitive ints are not stored with leading zeroes; you can just return the String instead of Integer.parseing it back to an int. e.g.
public static int lastTwoAsString(int digit){
String str = Integer.toString(digit);
String lastTwo = str.substring(str.length()-2);
return lastTwo;
}
If you indeed want to parse it back to an int, Java won't print leading zeroes by default. However, you can print leading zeroes of an int using use String.format. Note that you must specify a width to use the 0 modifier, in this case 2 makes the most sense:
public static void main(String[] args) {
int value = lastTwo(104);
String output = String.format("%02d", value);
System.out.println(output);
}
Output:
04
The last two digits of "104" is "04".
Then, the result of Integer.parseInt("04") is 4, because as an integer, the value of "04" is simply 4. And if you print the number 4, it's naturally printed as "4".
But why do you call Integer.parseInt at all?
The problem description seems underspecified.
It's not clear if the last two digits should be treated as a number or as a string.
If the last two digits should be a string, then your method should return a string.
If the last two digits should be a number, then instead of converting the input int to a String, it would be better to use the modulo operator:
static int lastTwo(int number) {
return number % 100;
}
static String lastTwoAsString(int number) {
String string = Integer.toString(number);
return string.substring(string.length() - 2);
}
The current method signature returns an int. As such, it cannot return 02. You will have to change it to String or format the output where the method is called.
If you can change the return type to String, you can do:
First way:
public static String lastTwo(int digit) {
String str = String.valueOf(digit);
return = str.substring(str.length() - 2);
}
Otherwise, where you call the method, you can format it:
String.format("%02d", lastTwo(digit))
Related
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;
As stated in the title, I would like to write a double in a string with a maximum number of character, in java.
Well actually to an exact number of character, but I can wrap it in a String.format("%Xs", ...) with given X to fill missing character.
Note that there are many questions related to this on SO and internet, but I couldn't find the exact same as mine for java.
What I think of would be to write
the full double if it fits: for max character n=10, 123.4567 is good
round decimal and keep the integer part if it fits: for n=10, 123456.789654 would format to 123456.79
use exponential otherwise: for n=10, 123456789123.321654 would format to 1.23457e11
=> Is there a practical tool to do that or something equivalent?
That is what I have for now, not perfect but I spend enough time on it already.
The idea is that Double.toString is doing exactly what I want but for a fixed length (maybe someone knows how to configure that length?). So I use it and remove decimal when necessary
/** write a double to a string of exact given length (but for some extreme cases) */
public static String doubleToString(double x, int length) {
String str = Double.toString(x);
if(str.length() <= length){
return org.apache.commons.lang.StringUtils.repeat(" ", length - str.length()) + str;
} else if(str.contains("E")){
String[] split = str.split("E");
String num = split[0];
String exp = split[1];
return removeDecimal(num, length - exp.length()-1) + 'E' + exp;
} else {
return removeDecimal(str, length);
}
}
// remove trailing decimal of a double as string such as xxx.yyyy
private static String removeDecimal(String doubleStr, int length){
int dotIndex = doubleStr.indexOf('.');
return doubleStr.substring(0, Math.max(dotIndex+1, length));
}
Take a look at BigDecimal (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html) I use new DecimalFormat("0.00") if I want to ensure that the two decimal places are always shown, e.g. 1000.5 will display as 1000.50.
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);
}
}
}
Below is a snippet of my java code.
//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
BigInteger temp = new BigInteger(binaryNumber, 2);
return temp.toString(16).toUpperCase();
}
If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits?
Thanks.
You do one of the following:
Manually pad with zeroes
Use String.format()
Manually pad with zeroes
Since you want extra leading zeroes when shorter than 4 digits, use this:
BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
hex = "000".substring(hex.length() - 1) + hex;
return hex;
Use String.format()
BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);
Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger.
In Java 8, do it by parsing the binary input as an unsigned number:
int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);
The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.
I customized your code a bit to include leading zeros based on input string:
public static void main(String[] args) {
System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
BigInteger temp = new BigInteger(binaryNumber, 2);
String hexStr = temp.toString(16).toUpperCase();
int b16inLen = binaryNumber.length()/4;
int b16outLen = hexStr.length();
int b16padding = b16inLen - b16outLen;
for (int i=0; i<b16padding; i++) {
hexStr=('0'+hexStr);
}
return hexStr;
}
Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.
So I have a set of base digits like "BCDFGHJKLMNPQRSTVWXZ34679"
how do I convert a value say "D6CN96W6WT" to binary string in Java?
This should work (assuming 0,1 for you binary digits):
// your arbitrary digits
private static final String DIGITS = "BCDFGHJKLMNPQRSTVWXZ34679";
public String base25ToBinary(String base25Number) {
long value = 0;
char[] base25Digits = base25Number.toCharArray();
for (char digit : base25Digits) {
value = value * 25 + DIGITS.indexOf(digit);
}
return Long.toString(value, 2);
}
Off the top of my head, for base-25 strings.
Integer.toString(Integer.valueof(base25str, 25), 2)
Its a little unclear from your question whether you're talking about actual 0-9-Z bases, or a number encoding with an arbitrary list of symbols. I'm assuming the first, if its the later then you're out of luck on built-ins.