Java adding "0" at the end of the number - java

So my problem was such that I had to compute 10^n such that n ~ 10^5. Obviously it wouldn't fit in any data type hence I decided to use a string instead.
Finally, I did find the solution in the beginners book
https://beginnersbook.com/2014/07/java-right-padding-a-string-with-spaces-and-zeros/.
I don't want the BigInteger solution of multiplying 10 n times.
public class PadRightExample2 {
public static void main(String[] argv) {
System.out.println("#" + rightPadZeros("mystring", 10) + "#");
System.out.println("#" + rightPadZeros("mystring", 15) + "#");
System.out.println("#" + rightPadZeros("mystring", 20) + "#");
}
public static String rightPadZeros(String str, int num) {
return String.format("%1$-" + num + "s", str).replace(' ', '0');
}
}
Output:
#mystring00#
#mystring0000000#
#mystring000000000000#
Can anybody explain what is %1$- and what is s used for ?

% stands for the format of String
1$ means the first additional parameter args of String.format(String format, Object... args), 2$ would be the second one, etc..
- is the left justification, in connection with number declares the length of the final output, briefly said. The documentation of java.util.Formatter explains is a bit better:
Left justifies the output. Spaces ('\u0020') will be added at the end of the converted value as required to fill the minimum width of the field.
s stands for the String parameter type
The typical example is logging, where you parse the arguments with %s which is practically the same. With a dollar character and number %1$s you specify the argument number and -10 makes the final output length of 10.
#mystring00# // mystring00 has length 10
#mystring0000000# // mystring0000000 has length 15
#mystring000000000000# // #mystring000000000000 has length 20
Most of the information could be found in the documentation of java.util.Formatter, which is used within String::format.
The snippet you have found might be a bit confusing because it works even without 1$ because the arguments are passed in order.
Try the following: String.format("%2$-" + num + "s", str, "test").replace(' ', '0');. The result will be
#test000000#
#test00000000000#
#test0000000000000000#
Whereas String.format("%1$-" + num + "s", str, "test").replace(' ', '0'); leads to the original result from your snippet. Notice the 1$ and 2$ difference.

Maybe I'm not understanding the question correctly, but cant you do:
public static String rightPadZeros(String str, int num) {
String add = "";
for(int i = 0; i < num;i++) add += "0";
return str + add;
}
I dont quite understand why you would want two zeros when num=10, but if you want that, do:
public static String rightPadZeros(String str, int num) {
String add = "";
for(int i = 0; i < num - 8;i++) add += "0";
return str + add;
}
EDIT: apparenetely that was bad for performance, so this might be better:
public static String rightPadZeros(String str, int num) {
return str + new String(new char[num]).replace("\0", "0");
}

Related

Produce an output that is the average letter in the string using charAt method and type-casting

I need to create a program that reads in a random word using a prompt.
The program needs to produce an output that is the average letter in the string.
If the average of the letters was 97.2 display a small a, but if the average of the letters was 97.5, display a small b.
I need to use type-casting and the charAt method that is part of the string class
This is all the information that I was given on what I have to do, and I am very confused. I don't have any code, because I don't even know where to start on this question. All help would be greatly appreciated.
Thank you! I really appreciate the feedback!
Here is my code post feedback:
public class Average_Of_String {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word;
System.out.println("say something");
word = scan.nextLine();
float sum = 0;
for(int i = 0; i < word.length(); i += 1) {
sum += word.charAt(i);
}
System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
int average = (int) (sum/word.length());
System.out.println((char) average);
}
}
Try this, code is simple and self-explanatory:
class Average {
public static void main(String[] args) {
String word = args[0]; // let us suppose you get the word this way
float sum = 0;
for(int i = 0; i < word.length(); i += 1) {
sum += word.charAt(i);
}
System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
}
}
The charAt function returns a character. Ascii Table states:
an ASCII code is the numerical representation of a character such as
'a' or '#' or an action of some sort
On that site you can see that a equals decimal 97 etc.

Splitting a string that has numbers and characters into an int and String

I have a String that goes "Peyton Manning; 49". Is there a way to have the computer read the left side of the String and make it equal to a new String "Peyton Manning" and take the right side of the String and make it equal to an int with a value of 49?
A number of ways spring to mind: you can tokenize or you can use regexs. You didn't specify about white space padding. Also, you didn't specify if the string segments around the delimiter can be invalid integers, mixtures strings digits etc. If this helped you, please mark accordingly.
public class Test {
public static void main(String[] args) {
String s="Blah; 99";
StringTokenizer st = new StringTokenizer(s, ";");
String name = st.nextToken();
Integer number = Integer.parseInt(st.nextToken().trim());
System.out.println(name.trim() + "---" + number);
number = Integer.parseInt(s.replaceAll("[^0-9]", ""));
name = s.replaceAll("[^A-Za-z]", "");
System.out.println(name + "---" + number);
int split = s.indexOf(";");
name = s.substring(0, split);
number = Integer.parseInt(s.substring(split+2, s.length()));
System.out.println(name + "---" + number);
}
}
The simplest way is:
String text = input.replaceAll(" *\\d*", "");
int number = Integer.parseInt(input.replaceAll("\\D", ""));
See KISS principle.

getting a number from a user and making changes and turning it into a string

I am making a math program that guesses the birthday of the user.
The user enters a number lets say : 75622 and i subtract a number from it to get the birthday, in this case 42682 -- 04/26/82
i want to be able to turn that integer into a string and then add the forward slash between the month, day and year.. and also add a 0 if it is only 5 digits and not 6 ( because of the month being 1-9).
I know how to use Integer.toString(int) to turn it into a string, but i do not know how to insert the forward slashes and the zero.
thank you kindly!
If you just want to convert the int to a String (with a leading 0) you can use String.format like
int num = 42682;
String s = String.format("%06d", num);
You might then use another String.format and String.substring to build your desired output, like
String output = String.format("%s/%s/%s", s.substring(0, 2),
s.substring(2, 4), s.substring(4));
System.out.println(output);
Which outputs (as requested)
04/26/82
Please find answer below:
public class CreateDateFromNumber {
public static void main(String[] args) {
int number = 42682;
System.out.println(getDate(number));
}
public static String getDate(int number) {
String numberStr = Integer.toString(number);
String outputStr = "";
if (numberStr.length() != 5 && numberStr.length() != 6) {
throw new IllegalArgumentException(
"Number should be length of 5 or 6");
}
if (numberStr.length() == 5) {
numberStr = "0" + numberStr;
}
int var0 = 0;
while (var0 < numberStr.length()) {
String var1 = numberStr.substring(var0, var0 + 2);
outputStr = outputStr + var1;
if (var0 + 2 < numberStr.length()) {
outputStr = outputStr + "/";
}
var0 = var0 + 2;
}
return outputStr;
}
}

Flipping binary numbers using recursion

I am working on a project that the user enters an odd binary number ex: 10101 and I am supposed to have a recursive method that will flip the 1's and 0's ex: 101 = 010. For some reason my code is getting rid of the leading zero making the number an even number which crashes the program. Any and all help is appreciated, below is my Recursive class that is supposed to do the work of flipping the binary digits.
public class Recursive2 {
// int digit;
String temp;
public Recursive2(int d){
//digit = d;
temp = recursive(Integer.toString(d));
//System.out.print(recursive(temp));
}
public String toString(){
return temp;
}
public String recursive(String a){
String tempStr = "";
if(a.length() % 2 == 0){
System.out.println("Even number");
return "";
}
else if(a.length() == 1){
if(a.equals("1")){
tempStr = "0";
// tempStr += d;
}
else if(a.equals("0")){
tempStr= "1";
}
//System.out.println("Flipped d to" + tempStr);
}
else{
tempStr += new Recursive2(Integer.parseInt(a.substring(0,1))).toString();
tempStr += new Recursive2(Integer.parseInt(a.substring(1, a.length() - 1))).toString();
tempStr += new Recursive2(Integer.parseInt(a.substring(a.length()-1, a.length()))).toString();
}
return tempStr;
}
Here is my main class that tests the recursion.
public static void main(String[] args){
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a Binary number with an odd amount of digits: ");
num = in.nextLine();
System.out.println(num);
int num2 = Integer.parseInt(num);
System.out.println(num2);
Recursive2 test = new Recursive2(num2);
System.out.println(test);
}
You made several mistakes:
Deciding if the number is odd or even should be done before calling recursive method. Currently, your code will stop after at most one invocation, because you check the number of bits.
There is no need to parse int and making it String again. The entire process can be done entirely with strings.
Constructing the result should consist of appending the result of recursive invocation without the last bit to the string representing the inverse of the last bit.
The base case should be a situation when the string is empty, not when the string has exactly one digit.
Fixing these mistakes will produce a correct implementation.
The current algorithm is beyond repair.
Here's a recursive algorithm that's very simple and that will work:
if the string is empty, return it
if the first char is 0, return "1" + recurse(s.substring(1))
otherwise (the first char is 1), return "0" + recurse(s.substring(1))
Leading zeros are ignored because you're converting the input binary number to integer. For an integer leading zeros don't mean anything. You should be working with String only.
Also Integer.parseInt(num); would assume that you want to parse a decimal number not binary. If you do want to parse a binary number then you'll have to use another overloaded method Integer.parseInt(String s, int radix)
However as I said, because of the leading zeros you should work only with the Strings.
Integer.parseInt(i) converts the String to its Integer value.
However the Integer value of 010 is 10, leading 0's are dropped.
Work with the input as a String to avoid this.
Use StringBuilder to avoid creating new String or you can use char array
public static void main(String[] args) {
int no = 1234; // some no
String in = Integer.toBinaryString(no);
System.out.println("Original " + in);
System.out.println("Flipped " + flipBits(in));
}
public static String flipBits(String in) {
if (in.length() % 2 == 0)
return "even length";
return new String(flipBits(in.toCharArray(), in.length() - 1));
}
private static char[] flipBits(char[] ch, int index) {
if (index < 0) {
return ch;
} else {
ch[index] = Character.forDigit(49 - ch[index], 2); //flip
return flipBits(ch, index - 1);
}
}
output
Original 10011010010
Flipped 01100101101
The problem is that you are converting to integer values, which will throw away leading zeros. Just deal with strings:
public static void main(String[] args){
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a Binary number with an odd amount of digits: ");
num = in.nextLine();
System.out.println(num);
String flipped;
if (num.length() % 2 == 0) {
flipped = "Even number";
else {
flipped = Recursive2.recursive(num);
}
System.out.println(flipped);
}
And the Recursive2 class can just have static methods:
public class Recursive2 {
private static String flip(char c) {
if (c == '0') return "1";
return "0"; // assumes characters are all 0 or 1
}
public static String recursive(String a) {
STring tempStr;
if (a.length() == 0) {
tempStr = "";
} else {
tempStr = flip(a.charAt(0)) + recursive(a.substring(1));
}
return tempStr;
}
}
You might want to throw an exception if you detect a character other than 0 or 1.
EDIT: Based on your comment, the recursive method can be written as:
public static String recursive(String a) {
String tempStr = flip(a.charAt(0));
final int len = a.length();
if (len > 1) {
tempStr += recursive(a.substring(1, len - 1)) + flip(a.charAt(len - 1));
}
return tempStr;
}
This assumes that the argument is an odd-length string. That check should be done outside the recursive method, since if it is true once, it is true at every subsequent recursion.
I'd advise you to instead, remove one digit from the String that the user has imputed, and convert it (from the 1 to 0 vise versa), then use sub-string as the pass for the recursive function with one less.
Hint-> the base case would be a.length() == 0; because if you remove one digit of the string you will eventually have the length be 0.
Good Luck!

How to check number of digits from BigDecimal?

The requirement is to check if the number of digits is less than 7 digits in that case insert in DB else don't. I have tried the following solutions:
First solution:
public static void checkNoOfDigitVal(BigDecimal bigDecVal) {
BigInteger digits = bigDecVal.toBigInteger();
BigInteger ten = BigInteger.valueOf(10);
int count = 0;
do {
digits = digits.divide(ten);
count++;
} while (!digits.equals(BigInteger.ZERO));
System.out.println("Number of digits : " + count);
}
First solution works fine sometimes but sometimes the condition in while loop is not satisfied and it keeps on increasing the count number leading to endless count.
Second solution:
public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
String string = bigDecVal.toString();
String[] splitedString = string.split("\\.");
String[] newVal = splitedString[0].split("");
int a = newVal.length - 1;
if (a <= 6) {
System.out.println("correct size insert into DB: " + a);
} else {
System.out.println("Incorrect size insert cancel: " + a);
}
}
For example, if the value is 999999.9999, the second solution will return newVal.length = 6.
Please suggest a better solution to check the number of digits for big decimal where looping overhead can be minimized.
You can get it trivially using:
static int integerDigits(BigDecimal n) {
n = n.stripTrailingZeros();
return n.precision() - n.scale();
}
The precision is the total number of digits, and the scale is how many of those are to the right of the decimal point, so the difference is how many are to the left of the decimal point.
EDIT it's necessary to remove any trailing zeros to get a correct result for e.g. 0.000
EDIT 2 alternatively (and acks to #AdrianShum), since the problem with trailing zeroes only manifests itself with 0.00... you could use:
static int integerDigits(BigDecimal n) {
return n.signum() == 0 ? 1 : n.precision() - n.scale();
}
Live demo at http://ideone.com/uI6iMG
There's a much better solution in Alnitak's answer, posted just after mine (but which I've only seen now). I guess I'll leave this since a couple of people have found it useful, but if I needed to do this, I'd use their approach, not the approach below.
Your second solution is close, but it doesn't have to be quite that complicated:
public static void checkNoOfDigitsVal(BigDecimal bigDecVal) {
String str = bigDecVal.toString();
int wholeNumberLength = str.split("\\.")[0].length();
if (wholeNumberLength <= 6) {
System.out.println("correct size insert into DB: " + wholeNumberLength);
} else {
System.out.println("Incorrect size insert cancel: " + wholeNumberLength);
}
}
Live Example
I'm assuming that your 999999.999 example should result in wholeNumberLnegth of 6 and therefore be inserted in the DB (the question is unclear about that).
Because the current answers are not robust enough IMO, Here's my solution.
This method will scale a BigDecimal to the given length, but only scales the fractional part. It will throw an Exception if the integer part will be scaled. For my use case this is what I want. Tweak it to your liking.
public static BigDecimal scaleBigDecimalToLength(BigDecimal bigDecimal, int length) throws NumbersUtilException {
int digitCount = bigDecimal.toPlainString().replaceAll("[.,-]", "").length();
if (digitCount > length) {
int scale = bigDecimal.scale();
int newScale = length - (digitCount - scale);
if (scale > 0 && newScale >= 0) {
bigDecimal = bigDecimal
.setScale(length - (digitCount - scale), RoundingMode.HALF_UP);
} else {
throw new NumbersUtilException(
String.format("Cannot scale %s to a length of %s", bigDecimal, length));
}
}
return bigDecimal;
}
scaleBigDecimalToLength(BigDecimal.valueOf(0.0000012345600000), 8)
Output: 0.0000012
If you want to ignore the Dot (".") and count. then try this :
int count = 0;
BigDecimal bigDecimal = new BigDecimal("123.1000");
String[] split = bigDecimal.toString()
.split("\\.");
for (String element : split) {
count = count + element.length();
}
System.out.println("Total digits are " + count);

Categories