Could you please share a java code snippet to convert 5 or 9 digit number to US ZIP code format
e.g.
Input -> Expected output
12345 -> 12345
123456789 -> 12345-6789
Below code works but for 5 digit it ends with -. How to remove this using regular expression?
public static void main(String[] args) throws ParseException {
String[] values = new String[]{"1234","12345","123456897"};
MaskFormatter f = new MaskFormatter("#####-####");
f.setValueContainsLiteralCharacters(false);
for(String value:values){
System.out.println(f.valueToString(value));
//System.out.println(String.format("%5s-%04s", value,value));
}
}
Output is:
234 -
12345-
12345-6897
Try,
String[] values = new String[]{"1234","12345","123456897"};
MaskFormatter f = new MaskFormatter("#####-####");
f.setValueContainsLiteralCharacters(false);
for(String value:values){
String output=f.valueToString(value).trim();
if(output.endsWith("-")){
output=output.substring(0,output.length()-1);
}
System.out.println(output);
//System.out.println(String.format("%5s-%04s", value,value));
}
Output:
1234
12345
12345-6897
public static String convertZip(String unconverted) {
if (unconverted.length() > 5) {
return unconverted.substring(0, 5) + "-" + unconverted.substring(5);
}
else {
return unconverted;
}
}
you can convert your number(any number of digit) to String and then validate the length and consider only length = 5 and length =9. Then you can take value as it is if length is 5. if length is 9 use substring() in Java and divide your String 0-5 and 5-9 then add - between two part. Now it is your zip code.
Just create two formatters and use the appropriate one based on the length of the value.
public static void main(String... args) throws ParseException {
String[] values = new String[] { "1234", "12345", "123456897" };
MaskFormatter f5 = new MaskFormatter("#####");
f5.setValueContainsLiteralCharacters(false);
MaskFormatter f9 = new MaskFormatter("#####-####");
f9.setValueContainsLiteralCharacters(false);
for (String value : values) {
System.out.println(value.length() > 5 ? f9.valueToString(value) : f5.valueToString(value));
}
}
Personally, I think I'd go in a different direction:
public static void main(String... args) throws ParseException {
String[] values = new String[] { "1234", "12345", "123456897" };
for (String value : values) {
System.out.println(value.length() > 5 ? new StringBuilder(value).insert(5, "-").toString() : value);
}
}
Try this,
var reformat = "123456789".replace(/(\d{5})/g, function(match){
return match + "-";
});
console.log(reformat.replace(/\-$/, ""));
Related
This is a snippet of my txt file "Q.txt".
12.54778255173505 : ^FinishedLine
15.416218875438748 :
^FinishedLine
16.245508427720914 : ^FinishedLine
9.595696051997852 : &^FinishedLine
11.971100145959943 : ! '^FinishedLine
11.678678199807727 : " $^FinishedLine
14.905855346233682 : # %^FinishedLine
15.98343143372184 : $ "^FinishedLine
16.053542916378102 : % #^FinishedLine
I need to sort my text file "Q.txt" which contains a double and a string.
It has been separated using " : " and at the end of each phrase there is ("^FinishedLine"). When I run this, all it is coming up with is a "NumberFormatException: empty string" error.
public class Sorting {
public static void sort() throws IOException {
Scanner s = new Scanner(new File("Q.txt"));
ArrayList<Qpair> set = new ArrayList<>();
String line = "";
while (s.hasNext()) {
String[] parts = line.split(" : ");
set.add(new Qpair(Double.parseDouble(parts[0]), parts[1]));
s.useDelimiter("^FinishedLine");
}
s.close();
System.out.println(set);
}
private static class Qpair{
private double d;
private String s;
public Qpair(double d, String s){
this.d = d;
this.s = s;
}
public double getDouble(){
return d;
}
public String getString(){
return s;
}
}
private static class QpairCompare implements Comparator<Qpair>{
public int compare(Qpair x, Qpair y){
return (int) (x.getDouble() - y.getDouble());
}
}
}
As far as I can see: You are setting line to the empty string. You enter the while loop without changing line. You split this empty string at :. I admit I had to try it out to be sure: it yields an array of 1 element, an empty string. You try to parse this empty string from the array as a double.
And you tell us you get NumberFormatException: empty string. Sounds like agreement to me.
I hope you can figure out what code line is missing and where you should insert it?
I have a simple textfile:
type = "hello"
number = 66
type = "hey"
number = 77
I'm basically just checking to see if the string "type" is found in the textfile, if yes, I'd also like to get the values "hello" and "hey" i.e the types. However, my program doesn't work at all in that sense it all always prints no, when checking if "type" is in the file.
public static void main(String[] args) {
if(args.length == 1)
parseText(argv[0]); // call with textfile name
}
public void parseText(String inPath) {
try {
Scanner s = new Scanner(inPath);
while(s.hasNextLine()) {
if("type".equals(s.nextLine().trim()))
System.out.println("Yes");
else {
System.out.println("no");
}
}
}catch (Exception e ) {
System.out.println("\nFILE NOT FOUND");
}
}
Any help would be much appreciated.
if("type".equals(s.nextLine().trim()))
You really want to read the line of data from the file into a String so you can do processing on the string.
You want to know if the line starts with "type":
String line = s.nextLine()
if (line.startsWith("type"))
{
String value = line.substring(8);
System.out.println(value);
}
Check if the line starts with "type" (not is equal to "type").
if("type".equals(s.nextLine().trim()))
should be something like
String line = s.nextLine().trim();
if (line.startsWith("type"))
Suppose I have java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K" which follows the same pattern "200$2$", where "$" is the placeholder. Now which is the most efficient way to get Set of just unique codes from such strings in Java?
Input: java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K"
Expected output: java.util.Set<String> of "YZ", "1Y", "89", "TK"
My Try ::
public static void getOutPut()
{
Set<String> input = new HashSet<String>();
Set<String> output = new HashSet<String>();
StringBuffer out = null;
for(String in : input)
{
out = new StringBuffer();
StringCharacterIterator sci = new StringCharacterIterator(in);
while (sci.current( ) != StringCharacterIterator.DONE){
if (sci.current( ) == '$')
{
out.append(in.charAt(sci.getIndex()));
}
sci.next( );
}
output.add(out.toString());
}
System.out.println(output);
}
It is working fine, but is there any efficient way than this to achieve it? I need to do it for more than 1000K codes.
Get the indexes of the placeholder in the pattern:
int i = pattern.getIndexOf('$');
You'll must to iterate to obtain all the indexes:
pattern.getIndexOf('$', lastIndex+1);
The loop and the checks are up to you.
Then use charAt with the indexes over each element of the set.
I am trying to read file and split its line to get some context(Computer Name and Date), the code gives few lines of outputs then gives the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at FILE_MAIN.getComputerName(FILE_MAIN.java:34)
at FILE_MAIN.readFiles(FILE_MAIN.java:24)
at FILE_MAIN.main(FILE_MAIN.java:12)
Code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class FILE_MAIN
{
public static void main(String[] args) throws FileNotFoundException
{
File folder = new File("folderName/");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
readFiles(listOfFiles[i].getName());
}
}
public static void readFiles(String fileName) throws FileNotFoundException
{
FileReader dataFile = new FileReader("yukt/"+fileName);
try (Scanner FileRead = new Scanner(dataFile))
{
while (FileRead.hasNextLine() && FileRead.nextLine().isEmpty()==false)
{
String[] split;
String line = FileRead.nextLine();
split = line.split("\\|",-1);
String computerName=getComputerName(split[0]);
System.out.println(computerName);
}
}
}
public static String getComputerName(String splited)
{
String[] split1;
String[] split2;
split1=splited.split("\\:",-1);
split2=split1[1].split("\\ ",-1);
return("a");
}
public static String getDate(String splited)
{
String[] split1=splited.split("\\(",-1);
String[] split2=split1[1].split("\\ ",-1);
return(split2[0]);
}
}
The main function gets names of the files in a folder, and passes each file to the readFiles function where each line is split into 3 parts by a delimeter(|) and parts are send to getComputerName and getDate function which returns its values after further splitting the strings.
Here is an example of a line of the file, all the lines are similar to this:
[CD8C] ComputerName:NITIN UserID:GO ankurjain Station 9900 LanId: | (11/24 19:50:30) | Client is disconnected from agent.
There is no protection for split1 containing a single element:
split1=splited.split("\\:",-1);
split2=split1[1].split("\\ ",-1); // Accesses second element of split1
Add protection and decide if it is an error for there to be no : in the input string or just use whole string if no ::
split1=splited.split("\\:",-1);
if (split1.length > 1)
{
split2=split1[1].split("\\ ",-1);
}
split1=splited.split("\\:",-1);
split2=split1[1].split("\\ ",-1);
split1 must not be doing what you think.
i.e. it is not splitting, cos split1[1] is not valid.
You should really check the result of the first split before trying to use it's results.
I had similar issue where I had to check weather string sub part contains given string or not. But String in question had many variation. Instead of using if loop I used ternary operator -
StringUtils.containsIgnoreCase("Test String",
("split me".split(":").length > 1)
? "split me".split(":")[1] : "Can't split")
split2=split1[1] gives you java.lang.ArrayIndexOutOfBoundsException: 1 the error. The Array does not have 2 elements so index on 1 will throw an error.
You could add a check to make sure it has atleast 2 elements by putting the assignement in a if statement
if (split1.lenght > 1){
split2=split1[1].split("\\ ",-1);
}
This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
I have an integer 100, how do I format it to look like 00000100 (always 8 digits long)?
Try this:
String formattedNumber = String.format("%08d", number);
You can also use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100
Yet another way. ;)
int x = ...
String text = (""+(500000000 + x)).substring(1);
-1 => 99999999 (nines complement)
import java.util.concurrent.Callable;
/* Prints.
String.format("%08d"): Time per call 3822
(""+(500000000+x)).substring(1): Time per call 593
Space holder: Time per call 730
*/
public class StringTimer {
public static void time(String description, Callable<String> test) {
try {
// warmup
for(int i=0;i<10*1000;i++)
test.call();
long start = System.nanoTime();
for(int i=0;i<100*1000;i++)
test.call();
long time = System.nanoTime() - start;
System.out.printf("%s: Time per call %d%n", description, time/100/1000);
} catch (Exception e) {
System.out.println(description+" failed");
e.printStackTrace();
}
}
public static void main(String... args) {
time("String.format(\"%08d\")", new Callable<String>() {
int i =0;
public String call() throws Exception {
return String.format("%08d", i++);
}
});
time("(\"\"+(500000000+x)).substring(1)", new Callable<String>() {
int i =0;
public String call() throws Exception {
return (""+(500000000+(i++))).substring(1);
}
});
time("Space holder", new Callable<String>() {
int i =0;
public String call() throws Exception {
String spaceHolder = "00000000";
String intString = String.valueOf(i++);
return spaceHolder.substring(intString.length()).concat(intString);
}
});
}
}
String.format uses a format string which is described here
If Google Guava is an Option:
String output = Strings.padStart("" + 100, 8, '0');
Alternatively Apache Commons Lang:
String output = StringUtils.leftPad("" + 100, 8, "0");
If you just need to print it out, this is a shorter version:
System.out.printf("%08d\n", number);
This also works:
int i = 53;
String spaceHolder = "00000000";
String intString = String.valueOf(i);
String string = spaceHolder.substring(intString.lenght()).contract(intString);
But the other examples are much easier.
If you need to parse this string and or support i18n consider extending the
java.text.Format
object. Use the other answers to help you get the format.