I have a constant that's negative and I want the output to come out as positive. When I add a %+f it doesn't do anything and the output still comes out -15,123.45?
public static final double n2 = -15123.456789;
System.out.printf("%+,.2f\n", n2);
The format string "%+,.2f\n" only defines the formatting in which value must be printed. It doesn't change the actual value. If your input value is negative, the output string will display it as negative. It's like, when you make something bold, it doesn't change to another thing.
To convert the value to the opposite sign (- to +, + to -), you can multiply the value by -1: Thanks to kjbartel for the shortcut.
System.out.printf("%+,.2f\n", -1 * n2);
// or
System.out.printf("%+,.2f\n", -n2);
To convert the value to always be positive (- to +, + to +), you can use Math.abs: Thanks to zubergu for the tip.
System.out.printf("%+,.2f\n", Math.abs(n2));
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 have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is:
The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing.
It is also hard to check if the given int is positive or negative.
The regulations:
I'm only allowed to use the arithmetic operation + and all the boolean operations. But in this case I know that I have to use XOR.
It's not about writing the method and all the JAVA stuff. It's just the logic I struggle with.
How can I change a value to its negative value using only XOR and +?
ATTENTION:
The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit:
The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.
(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1. -1 has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1, all you need to do is invert and add 1.
Here we go
public class Test {
public static void main(String []args){
int x = 245;
System.out.println(x);
x = (~x^x)*x;
System.out.println(x);
}
}
With below code sample why the first addition (1/2+1/2) prints 0 but the second addition prints 00.
System.out.println(1/2+1/2+"=1/2+1/2");
System.out.println("1/2+1/2="+1/2+1/2);
Output:
0=1/2+1/2
1/2+1/2=00
Integer math (int 1 divided by int 2 is int 0, if you want a floating point result cast one, or both, of 1 and 2 to a floating point type) and order of operations, the second example is String concatenation. The compiler turns that into
System.out.println(new StringBuilder("1/2+1/2=").append(1/2).append(1/2));
and then you get
System.out.println(new StringBuilder("1/2+1/2=").append(0).append(0));
The first statement "System.out.println(1/2+1/2+"=1/2+1/2");" prints 0 because an the integer value obtained from 1/2 is zero. The remainder is dropped and since 1/2 equals 0.5 the .5 is dropped.
The second statement "System.out.println("1/2+1/2="+1/2+1/2);" prints out 00 because of the concatenation sign. In the second statement the first integer 1 is shown as +1 so the statement is actually being read as (+1/2 +1/2) which is why it returns 00.
If the second statement was set up like this:
System.out.println("1/2+1/2="+ (1/2+1/2));
The output would be the same as the first statement.
Expression is evaluated from left to right. In the first case it does int+int (which is 0), then int + "= String" which is a String tmp = "0= String". In the other case you have '"String =" + intwhich becomes"String =int"to which you append one moreint`. Thus you print String, "0" and "0".
java assumes that the result of the division is integer , since its members are integers. For the floating result ( 0.5 ) of each division , the divisor or the dividend should be of type float
System.out.println("1/2+1/2="+(1/2.0+1/2.0));
PS: I tried searching many existing questions here on Stackoverflow, however it
only added chaos to my query!
10101
11100
11010
00101
Consider this as a sample Input, which I need to read as BinaryString one by one! Then I need to represent them as an Integer.
Obviously int x = 20 initializes x as a decimal Integer,
and I read from other questions that int y = 0b101 initializes y as a binary Integer.
Now, The question is: If I have a binaryString, how do I cast it into an int like with a preceding 0b . My objectives following this is to perform bit level OR and XOR operations.
ie from the above input, I need to do 10101 ^ 11100
Let me know if this is the right way to approach a problem like this, Thanks!
If I have understood your question correctly, you want to know how to represent Binary Strings as Integer.
Well, you can perform this task for conversion of Binary String to Integer:
String input = "0b1001";
String temp = input.substring(2);
int foo = Integer.parseInt(temp, 2);
Alternately, to switch back :
String temp = Integer.toBinaryString(foo);
from the above input, I need to do 10101 ^ 11100.
You can achieve the same using proper decimal representation of integer. If you want to re-invent the wheel, then
first convert the decimal representation of the given number to Binary String(using step 2);
then convert to integer value using step 1;
repeat steps 1 and 2 for the second number; and
finally, perform the XOR operation over them.
But, I don't see how it'll be performing/calculating differently. It'd still be stored as the same integer. It is just that you will get extra satisfaction(on your part) that the number was read as an integer and then converted to Binary representation of that number.
Try Integer.parseInt(String s, int radix). It will throw an exception if the binary string is invalid, so you might want to validate the input.
String binary = "10001";
int asInt = Integer.parseInt(binary, 2); // 17
int supports ^ (bitwise XOR) operator. All you have to do is convert your binary strings to int variables and perform the desired operations.
I need to put a constraint for negative values on string variable. For Eg :--
string zeroval = "0.0000"
String x = "";
if (x==null) || (x.equals(zeroval)) { // code which checks if string x has 0 or null value
x = "--" // replace it by --
}
similarly i want to add another piece of code which checks if String x contains any negative values (for eg : "-0.025") and replace it by --
The above String x should not contain null/zero/negative values
Please help
Note :- In order to add negative value check convert the string to float as i cannot use pattern matching technique for eg:- x.equals("-")
Is your input data always meant to contain valid numbers? If so, you could just use:
BigDecimal number = new BigDecimal(text);
if (number.compareTo(BigDecimal.ZERO) <= 0) {
text = "--";
}
This will validate that it really is a number as well as performing the check. Additionally:
It copes with other representations of 0, e.g. "0.00", "0", "+0"
It uses BigDecimal to avoid oddities in binary floating point representations (e.g. a very small positive value being seen as 0). Unlikely to be a problem, but fundamentally you've got decimal data, so you might as well parse it that way.
Convert it to Integer or double using wrapper class.
String number="12.3434"
if(Double.parseDouble(number)<0)
//do stuff here
You could check if the string starts with a "-":
if (x==null) || (x.equals(zeroval) || x.startsWith("-")) {
x = "--";
}
I can't help but feel you are doing something ill-advised by using Strings to represent numerical data.
You could use Double.parseDouble(String) or Float.parseFloat (String). These methods will help you get a double or a float, respectively.
After this, you can easily check if the value is negative.