Read data from barcode - java

I have one question regarding about retrieving Barcode data.
Below screen shot is the my java application.
For example, the barcode data have "12345-6789".
I put cursor on "Mo No." and scan barcode, System will read barcode and display on "Mo No." filled as "12345-6789"
But what I want is "12345" in Mo No. and "6789" in Container No. Once I scanned barcode.
How should I implement the code.
Please advice.Thanks.

you can just ignore whatever after dash -
for example:
String barcode="12345-6789";
System.out.println(barcode.substring(0,barcode.indexOf("-"))); //this will only print whatever before first occurance of '-'
OUTPUT:
12345

Use String#split
String toSplit = "12345-6789";
String a;
String b;
//check if string contains your split-char with [string#contains][2])
if(toSplit.contains("-")
{
//split takes RegularExpression!
String[] parts = toSplit.split("-");
a = parts[0]; // =12345
b = parts[1]; // =6789
}
else
{
throw new IllegalArgumentException(toSplit + " does not contain -");
}

Related

Java - String splitting

I read a txt with data in the following format: Name Address Hobbies
Example(Bob Smith ABC Street Swimming)
and Assigned it into String z
Then I used z.split to separate each field using " " as the delimiter(space) but it separated Bob Smith into two different strings while it should be as one field, same with the address. Is there a method I can use to get it in the particular format I want?
P.S Apologies if I explained it vaguely, English isn't my first language.
String z;
try {
BufferedReader br = new BufferedReader(new FileReader("desc.txt"));
z = br.readLine();
} catch(IOException io) {
io.printStackTrace();
}
String[] temp = z.split(" ");
If the format of name and address parts is fixed to consist of two parts, you could just join them:
String z = ""; // z must be initialized
// use try-with-resources to ensure the reader is closed properly
try (BufferedReader br = new BufferedReader(new FileReader("desc.txt"))) {
z = br.readLine();
} catch(IOException io) {
io.printStackTrace();
}
String[] temp = z.split(" ");
String name = String.join(" ", temp[0], temp[1]);
String address = String.join(" ", temp[2], temp[3]);
String hobby = temp[4];
Another option could be to create a format string as a regular expression and use it to parse the input line using named groups (?<group_name>capturing text):
// use named groups to define parts of the line
Pattern format = Pattern.compile("(?<name>\\w+\\s\\w+)\\s(?<address>\\w+\\s\\w+)\\s(?<hobby>\\w+)");
Matcher match = format.matcher(z);
if (match.matches()) {
String name = match.group("name");
String address = match.group("address");
String hobby = match.group("hobby");
System.out.printf("Input line matched: name=%s address=%s hobby=%s%n", name, address, hobby);
} else {
System.out.println("Input line not matching: " + z);
}
I can think of three solutions.
In order from best to worst:
Different delimiter
Enforce the format to always have two names, two address parts and one hobby
Have a dictionary with names and hobbies, check each word to determine which type it is and then group them together as needed.
(The 3rd option is not meant as a serious alternative.)
As others have mentioned, using spaces as both field delimiter and inside fields is problematic. You could use a regex pattern to split the line (paste (\w+ \w+) (\w+ \w+) (.+) in Regex101 for an explanation):
Pattern pattern = Pattern.compile("(\\w+ \\w+) (\\w+ \\w+) (.+)");
Matcher matcher = pattern.matcher("Bob Smith ABC Street Bowling Fishing Rollerblading");
System.out.println("matcher.matches() = " + matcher.matches());
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println("matcher.group(" + i + ") = " + matcher.group(i));
}
This would give the following output:
matcher.matches() = true
matcher.group(0) = Bob Smith ABC Street Bowling Fishing Rollerblading
matcher.group(1) = Bob Smith
matcher.group(2) = ABC Street
matcher.group(3) = Bowling Fishing Rollerblading
However this only works for this exact format. If you get a line with three name parts for example:
John B Smith ABC Street Swimming
This will get split into John B as the name, Smith ABC as the address and Street Swimming as hobbies.
So either make 100% sure your input will always match this format or use a different delimiter.
The split() method majorly works on the 2 things:
Delimiter and
The String Object
Sometimes on limit too.
Whatever limit you will provide, the split() method will do its work according to that.
It doesn't understand whether the left substring is a name or not, same as for the right substring.
Have a look at this code snippet:
String assets = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = assets.split(":");
System.out.println("splits.size: " + splits.length);
for(String asset: splits){
System.out.println(assets);
}
OutPut
splits.size: 5
Gold
Stocks
Fixed Income // with space
Commodity
Interest Rates // with space
The output came with spaces because I provided the ; as a delimiter.
This probably helped you to get your answer.
Find Detailed Information on Split():
Top 5 Use cases of Split()
Java Docs : Split()
It depends on the data you're dealing with. Will the name always consist of a first and last name? Then you can simply combine the first two elements from the resulting array into a new string.
Otherwise, you might have to find a different way to separate out the different pieces within the txt file. Possibly a comma? Some character that you know won't ever be used in your normal data.
Assuming that every line follows the format
Bob Smith ABC Street Swimming
ie, name surname.... this code can manually manipulate the data for you:
String[] temp = z.split(" ");
String[] temp2 = new String[temp.length - 1];
temp2[0] = temp[0] + " " + temp[1];
for (int i = 2; i < temp.length; i++) {
temp2[i] = temp2[i];
}
temp = temp2;

Splitting a user inputted string and then printing the string

I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored

read from file with space delimiter

hello guys I need help with reading from file with space delimiter. The problem is for example i got a text file the format as follows: id name
example:
1 my name
how can I get the string together (my name) as the code I have tried would only get me (my). I can't change the delimiter from the text file
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
String readData[] = readLine.split(" ");
String index = readData[0];
String name = readData[1];
}
myScanner.close();
If it's always just going to be id space name with nothing coming after it, then you can do this:
String readLine = myScanner.nextLine();
int split = readLine.indexOf(" ");
String index = readLine.substring(0, split);
String name = readLine.substring(split + 1);
This will only work if those are the only two fields though. If you add more fields after that there's no (general) way to determine where item two ends and item three begins.
Another way is to use next, nextInt, etc, to read out exactly what you want:
String index = myScanner.next(); //Or int index = myScanner.nextInt();
String name = myScanner.nextLine().substring(1); //drop the leading space
That's a bit more flexible of an approach, which might be better suited to your needs.
Use following code.
while(myScanner.hasNextLine())
{
String readLine = myScanner.nextLine();
if(null != readLine && readLine.length()>0) {
String index = readLine.substring(0, id.indexOf(" "));
String name = readLine.substring(id.indexOf(" ") + 1);
}
}
myScanner.close();

Java Regex : How to search a text or a phrase in a large text

I have a large text file and I need to search a word or a phrase in the file line by line and output the line with the text found in it.
For example, the sample text is
And the earth was without form,
Where [art] thou?
if the user search for thou word, the only line to be display is
Where [art] thou?
and if the user search for the earth, the first line should be displayed.
I tried using the contains function but it will display also the without when searching only for thou.
This is my sample code :
String[] verseList = TextIO.readFile("pentateuch.txt");
Scanner kbd = new Scanner(System.in);
int counter = 0;
for (int i = 0; i < verseList.length; i++) {
String[] data = verseList[i].split("\t");
String[] info3 = data[3].split(" ");
System.out.print("Search for: ");
String txtSearch = kbd.nextLine();
LinkedList<String> searchedList = new LinkedList<String>();
for (String bible : verseList){
if (bible.contains(txtSearch)){
searchedList.add(bible);
counter++;
}
}
if (searchedList.size() > 0){
for (String s : searchedList){
String[] searchedData = s.split("\t");
System.out.printf("%s - %s - %s - %s \n",searchedData[0], searchedData[1], searchedData[2], searchedData[3]);
}
}
System.out.print("Total: " + counter);
So I am thinking of using regex but I don't know how.
Can anyone help? Thank you.
Since sometimes variables have non-word characters at boundary positions, you cannot rely on \b word boundary.
In such cases, it is safer to use look-arounds (?<!\w) and (?!\w), i.e. in Java, something like:
"(?<!\\w)" + searchedData[n] + "(?!\\w)"
To match a String that contains a word, use this code:
String txtSearch; // eg "thou"
if (str.matches(".*?\\b" + txtSearch + "\\b.*"))
// it matches
This code builds a regex that only matches if both ends of txtSearch fall and the start/end of a word in the string by using \b, which means "word boundary".

How to include white spaces in next() without using nextLine() in Java

I am trying to make the user input a string, which can both contain spaces or not. So in that, I'm using NextLine();
However, i'm trying to search a text file with that string, therefore i'm using next() to store each string it goes through with the scanner, I tried using NextLine() but it would take the whole line, I just need the words before a comma.
so far here's my code
System.out.print("Cool, now give me your Airport Name: ");
String AirportName = kb.nextLine();
AirportName = AirportName + ",";
while (myFile.hasNextLine()) {
ATA = myFile.next();
city = myFile.next();
country = myFile.next();
myFile.nextLine();
// System.out.println(city);
if (city.equalsIgnoreCase(AirportName)) {
result++;
System.out.println("The IATA code for "+AirportName.substring(0, AirportName.length()-1) + " is: " +ATA.substring(0, ATA.length()-1));
break;
}
}
The code works when the user inputs a word with no spaces, but when they input two words, the condition isn't met.
the text file just includes a number of Airports, their IATA, city, and country. Here's a sample:
ADL, Adelaide, Australia
IXE, Mangalore, India
BOM, Mumbai, India
PPP, Proserpine Queensland, Australia
By default, next() searches for first whitespace as a delimiter. You can change this behaviour like this:
Scanner s = new Scanner(input);
s.useDelimiter("\\s*,\\s*");
By this, s.next() will match commas as delimiters for your input (preceeded or followed by zero or more whitespaces)
Check out the String#split method.
Here's an example:
String test = "ADL, Adelaide, Australia\n"
+ "IXE, Mangalore, India\n"
+ "BOM, Mumbai, India\n"
+ "PPP, Proserpine Queensland, Australia\n";
Scanner scan = new Scanner(test);
String strings[] = null;
while(scan.hasNextLine()) {
// ",\\s" matches one comma followed by one white space ", "
strings = scan.nextLine().split(",\\s");
for(String tmp: strings) {
System.out.println(tmp);
}
}
Output:
ADL
Adelaide
Australia
IXE
Mangalore
India
BOM
Mumbai
India
PPP
Proserpine Queensland
Australia

Categories

Resources