Java String new line with specific logic and without string format - java

The following code:
String a = "100.00";
String b = "10.00";
String c= "5.00";
String value = a+ "\n"+ b +"\n" +c;
System.out.println(value);
Prints:
100.00
10.00
5.00
I need output in a format where decimal point position will be fixed without using any string format library (with logic):
100.00
10.00
5.00
Variable values are coming from the database and requirement is to show values with the decimal point in the same position with values vertically.

Here's an example using streams; probably could be more efficient but I was having fun.
It assumes all have 2 decimals as you showed, just FYI; that could be modified though.
String a = "100.00";
String b = "10.00";
String c= "5.00";
List<String> strings = Arrays.asList(a, b, c);
final int maxLen = strings.stream().map(String::length).reduce(Math::max).get();
strings.forEach(s -> {
System.out.println(Stream.generate(() -> " ").limit(maxLen - s.length()).collect(Collectors.joining()) + s);
});
Results:
100.00
10.00
5.00
I also put pthe 3 examples into a list so it would work on an arbitrary number of elements.
Without Java 8
String a = "100.00";
String b = "10.00";
String c = "5.00";
List<String> strings = Arrays.asList(a, b, c);
int maxLen = -1;
for (String s : strings) maxLen = Math.max(maxLen, s.length());
for (String s : strings) {
String spaces = "";
for (int i = 0; i < maxLen - s.length(); ++i) {
spaces += " ";
}
System.out.println(spaces += s);
}

I don't know what 'don't use any String format library' means specifically, but... now we get into a semantic argument as to what 'library' means. You're formatting a string. If I take your question on face value you're asking for literally the impossible: How does one format a string without formatting a string?
I'm going to assume you meant: Without adding a third party dependency.
In which case, if you have doubles (or BigDecimal or float) as input:
String.format("%6.2f", 100.00);
String.format("%6.2f", 10.00);
String.format("%6.2f", 5.00);
(6? Yes; 6! The 6 is the total # of characters to print at minimum. You want 3 digits before the separator, a separator, and 2 digits after, that's a grand total of 6, hence the 6.)
If you have strings as input, evidently you are asking to right-justify them? Well, you can do that:
String.format("%6s", "100.00");
String.format("%6s", "10.00");
String.format("%6s", "5.00");
NB: For convenience, System.out.printf("%6s\n", "100.0"); is short for System.out.println(String.format("%6s", "100.0"));

Related

Converting a hexadecimal string to integer value without pre-made syntax

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;

How to set width AND pad integer witdth String Formatter in Java

Given I have the following integers:
1, 10, 100
I want to pad them with zeroes to have exactly 3 digits:
001
010
100
and I want to print them prefixed by 10 spaces:
001 //assume 10 spaces from the beginning of the line
010
100
I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.
Below are 2 expressions that I created that accomplish each one of these conditions:
#Test
public void test1() {
String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
int[] nums = {1, 10, 100};
for (int i = 0; i < 3; i++) {
String s = langs[i];
int n = nums[i];
System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
}
}
According to documentation the formatter string has the below form:
%[argument_index$][flags][width][.precision]conversion
but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".
How can this be rewritten to accomplish the above mentioned conditions?
NOTE:
My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:
System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);
EDIT:
My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:
textX 001
textXXX 010
textXX 100
So that the spacing is variable.
If the two only criterias are the padding of 10 Spaces and zero-padding of the numbers:
final String str = String.format("%10s%03d", " ", 2);
Edit after update from OP:
System.out.printf("%-10s%03d", "abc", 2);
How it Works:
We need two arguments for Our pattern, one for the String of length 10, and one for the integer.
%10s is a pattern for a String of length 10. In order to left align it, we add the -: %-10s. The second argument is the integer of length 3 that we want to left pad With zero: %03d.
If we dont want to rearrange or reuse an argument for multiple format specifiers, just pass the arguments in the order specified in the pattern.
This answer is based on your latest edit, which revealed this data:
textX 001
textXXX 010
textXX 100
Assuming that the second column always has a width of 3, then your problem distills down to figuring out how many spaces need to be added after the first text column. Here is how you could do this in Java 7:
String text = "textXXX";
int n = 10 - text.length();
String padding = String.format("%0" + n + "d", 0).replace("0", " ");
In Java 8 you could this to get the padding string:
String padding = String.join("", Collections.nCopies(n, " "));

java - Enforce 4 digit hex representation of a binary number

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'.

Convert Floating point double to non floating point string

I have the following number:
1.0645208E10, which is in my case a double value. I would like to convert it into 106.45.
Any recommendation how to get 106.45?
I appreciate your answers!
You can try this:
double bigDouble = 1.0645208E10;
String strDouble = String.format(Locale.ENGLISH, "%.2f", bigDouble/100000000);
System.out.println(strDouble);
It will give you 106.45
But be aware of the fact that the output has nothing to do with the original value!! Is one hundred million times smaller...
Any recommendation how to get 106.45?
If you want to get only output then you can do following.
Double d = 1.0645208E10;
String s = d.toString().replace(".", "");//Converts into string and removes dot (.)
String s1 = s.substring(0, 5);//it gets only first 5 characters
String s2 = s1.substring(0, 3) + "." + s1.substring(3, 5);//it adds decimal point after first 3 character
System.out.println("Expected Output: " + s2);

Add leading zeroes to number in Java? [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
In your case it will be:
String formatted = String.format("%03d", num);
0 - to pad with zeros
3 - to set width to 3
Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.
Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:
static String intToString(int num, int digits) {
assert digits > 0 : "Invalid number of digits";
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
How about just:
public static String intToString(int num, int digits) {
String output = Integer.toString(num);
while (output.length() < digits) output = "0" + output;
return output;
}
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

Categories