I've been working with the printf function for a bit now and was wondering if there was a way to use declared variables within the formatting section of printf? Something like:
int x = 5;
System.out.printf("%0xs\n", text);
// Normally this would be "%05s\n"
Meaning that I can use "x" as a changeable variable to be able to change how many 0 it can have. I am asking because I was given a code where the first line will give me a number, which is the amount of 0 I have to put before the text. Is something like this possible?
I don't think that you can do it in a singular String.format statement. However I was able to do with nested format.
final int padding = 5;
System.out.printf(String.format("%%0%dd%%n", padding), 7);
System.out.printf(String.format("%%%ds%%n", padding), "hey");
Output:
00007
hey
Also, you can use %n to insert an end line character automatically.
Related
sorry for the title but couldn't really express this in another way.
So, let's say I have a variable that represents a prescription's unique code. I already know that there a total of 400 prescriptions. So for every new prescription I would like that code to change by one. The first one I want it to be 001, the second one 002 etc. I know I can just set a static int but how can I make the 0's appear in the front so it prints 001 and not just 1? I am new to java so I might be asking a really stupid question. Thanks for your time!
You can format it with Java format specifiers.
Here would be the code to do that:
int prescriptionCode = 1;
System.out.println(String.format("%03d", prescriptionCode));
The string "%03d" is the format specifier. Going backwards, "d" indicates that the value you want here is a decimal, "3" indicates that you want the value to be 3 characters long regardless of its actual length, "0" means that you want to fill the remaining space the number doesn't take up with 0's.
Relatively new to programming here so I apologize if this is rather basic.
I am trying to convert string lines into actual variables of different types.
My input is a file in the following format:
double d1, d2 = 3.14, d3;
int a, b = 17, c, g;
global int gInt = 1;
final int fInt = 2;
String s1, s2 = "Still with me?", s3;
These lines are all strings at this point. I wish to extract the variables from the strings and receive the actual variables so I can use and manipulate them.
So far I've tried using regex but I'm stumbling here. Would love some direction as to how this is possible.
I thought of making a general type format for example:
public class IntType{
boolean finalFlag;
boolean globalFlag;
String variableName;
IntType(String variableName, boolean finalFlag, boolean globalFlag){
this.finalflag = finalFlag;
this.globalFlag = globalFlag;
this.variableName = variableName;
}
}
Creating a new wrapper for each of the variable types.
By using and manipulating I would like to then compare between the wrappers I've created and check for duplicate declarations etc'.
But I don't know if I'm on the right path.
Note: Disregard bad format (i.e. no ";" at the end and so on)
While others said that this is not possible, it actually is. However it goes somewhat deep into Java. Just search for java dynamic classloading. For example here:
Method to dynamically load java class files
It allows you do dynamically load a java file at runtime. However your current input does not look like a java file but it can easily be converted to one by wrapping it with a small wrapper class like:
public class CodeWrapper() {
// Insert code from file here
}
You can do this with easy file or text manipulations before loading the ressource as class.
After you have loaded the class you can access its variables via reflection, for example by
Field[] fields = myClassObject.getClass().getFields();
This allows you to access the visibility modifier, the type of the variable, the name, the content and more.
Of course this approach presumes that your code actually is valid java code.
If it is not and you are trying to confirm if it is, you can try to load it. If it fails, it was non-valid.
I have no experience with Java, but as far as my knowledge serves me, it is not possible to actually create variables using a file in any language. You'll want to create some sort of list object which can hold a variable amount of items of a certain type. Then you can read the values from a file, parse them to the type you want it to be, and then save it to the list of the corresponding type.
EDIT:
If I were you, I would change my file layout if possible. It would then look something like this:
1 2 3 4 //1 int, 2 floats, 3 booleans and 4 strings
53
3.14
2.8272
true
false
false
#etc.
In pseudo code, you would then read it as follows:
string[] input = file.Readline().split(' '); // Read the first line and split on the space character
int[] integers = new int[int.Parse(input[0])] // initialise an array with specefied elements
// Make an array for floats and booleans and strings the same way
while(not file.eof) // While you have not reached the end of the file
{
integers.insert(int.Parse(file.ReadLine())) // parse your values according to the size which was given on the first line of the file
}
If you can not change the file layout, then you'll have to do some smart string splitting to extract the values from the file and then create some sort of dynamic array which resizes as you add more values to it.
MORE EDITS:
Based on your comment:
You'll want to split on the '=' character first. From the first half of the split, you'll want to search for a type and from the second half, you can split again on the ',' to find all the values.
here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.
I'm just getting started with Talend and I would like to know how to divide a value from a CSV file and round it if possible?
Here's my job layout:
And here's how my tMap is configured:
I assume the "/r" is to add a new line? That won't actually work and will instead add a string literal "/r" to whatever other string you're adding it to. You also don't need to do that because Talend will automatically start a new line at the end of the row of data for your tFileOutputDelimited.
But more importantly, you're attempting to call the divide method on a string which obviously doesn't exist (how would it be defined?).
You need to first parse the string as a numeric type (such as float/double/Big Decimal) and then divide by another numeric type (your Var1 is defined as a string in your example, so will actually fail there too because a string must be contained in quotes).
So typically you would either define the schema column that you are dividing as a numeric type (as mentioned) or you'd attempt to parse the string into a float in the tMap/tJavaRow component.
If you have your prices defined as something like a double before your tMap/tJavaRow operation that divides then you can use:
row1.prix2 / Var.var1
Or to round it to two decimal places:
(double)Math.round((row1.prix2 / Var.var1) * 100) / 100
You can also use a tConvertType component to explicitly convert between types where available. Alternatively you could parse the string as a double using:
Double.parseDouble(row1.prix2)
And then proceed to use that as previously described.
In your case though (according to your comment on Gabriele's answer), there is a further issue in that Java (and most programming languages) expect numbers to be formatted with a . for the decimal point. You need to add a pre-processing step to be able to parse your string as a double.
As this question's answers show, there are a couple of options. You can use a regex processing step to change all of your commas in that field to periods or you can use a tJavaRow to set your locale to French as you parse the double like so:
NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
Number number = format.parse(input_row.prix2);
double d = number.doubleValue();
output_row.nom = input_row.nom;
output_row.code = input_row.code;
output_row.date = input_row.date;
output_row.ref = input_row.ref;
output_row.ean = input_row.ean;
output_row.quantitie = input_row.quantitie;
output_row.prix1 = input_row.prix1;
output_row.prix2 = d;
And make sure to import the relevant libraries in the Advanced Settings tab of the tJavaRow component:
import java.text.NumberFormat;
import java.util.Locale;
Your output schema for the tJavaRow should be the same as the input but with prix2 being a double rather than a string.
Since var1 is defined as String you cannot apply the divide method. Try something like this for your output prix2 calculus:
(Float.parseFloat(row1.prix2)/2200f) + "Vr"
or something like that (I cannot read the text in the screenshot very well, actually)
This is basically what I am trying to do
// ... some code, calculations, what have you ...
long timeToAdd = returnTimeToAddInLongFormat();
// lets output the long type now, and yes i need the width and precision.
System.out.printf("Time to add: %13.10ld", timeToAdd);
I've read most of the google searches around the topic and think I understand how to do it conceptually, but the JRE keeps throwing me a UnknownFormatConversionException and telling me my input size modifier l doesnt work.
Is there another way to do this, or did I miss something small?
Java treats all integer values as d, there is no ld. Even byte and BigInteger is a d type. It also assumes integers have no decimal places. If you want to show 10 zeros, you can convert to double first and use f