Ignore characters in between quote - java

I have several strings like this from a file, my code tells it to split each line by a comma and if a line is author, output it, if it is title output it, e.t.c. As labelled, no 2 prints out the output but no 1 prints out only title and journal, i basically think its because of the characters in between, here is my code that splits, how do i tell it to ignore the characters in between or replace them.
1. #Article{Balogh:2015:OBW,
author = "J{\'a}nos Balogh and J{\'o}zsef B{\'e}k{\'e}si and
Gy{\"o}rgy D{\'o}sa and Leah Epstein and Hans Kellerer
and Asaf Levin and Zsolt Tuza",
title = "Offline black and white bin packing",
journal = {Theor. Comput. Sci.}
}
2.#Article{DAngelo:2015:MSP,
author = "Gianlorenzo D'Angelo and Daniele Diodati and Alfredo
Navarra and Cristina M. Pinotti",
title = "The minimum $k$-storage problem on directed graphs",
journal = {Theor. Comput. Sci.}
}
Code that splits.
printArray = InArray[i].trim().split( ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))" ,-1);
i have tried this
printArray = InArray[i].trim().split(",");
this
//InArray[i]=InArray[i].replaceAll("[{}]","").replaceAll("[\\\"]", "");
printArray = InArray[i].trim().split( ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))" ,-1);
but i keep getting index out of bound exception

I basically did this to fix this.
printArray = InArray[i].replaceAll("\\\\\"", "").trim().split(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))

Related

Stop printing line of text from a file after a character appears a second time

I am currently trying to stop printing a line of text after a , character is read on that line a second time from a text file. Example; 14, "Stanley #2 Philips Screwdriver", true, 6.95. Stop reading and print out the text after the , character is read a second time. So the output text should look like 14, "Stanley #2 Philips Screwdriver". I tried to use a limit on the regex to achieve this but, it just omits all the commas and prints out the entire text. This is what my code looks like so far;
public static void fileReader() throws FileNotFoundException {
File file = new File("/Users/14077/Downloads/inventory.txt");
Scanner scan = new Scanner(file);
String test = "4452";
while (scan.hasNext()) {
String line = scan.nextLine();
String[] itemID = line.split(",", 5); //attempt to use a regex limit
if(itemID[0].equals(test)) {
for(String a : itemID)
System.out.println(a);
}//end if
}//end while
}//end fileReader
I also tried to print just part of the text up until the first comma like;
String itemID[] = line.split(",", 5);
System.out.println(itemID[0]);
But no luck, it just prints 14. Please any help will be appreciated.
What about something using String.indexOf and String.substring functions (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html)
int indexSecondOccurence = line.indexOf(",", line.indexOf(",") + 1);
System.out.println(line.substring(0, indexSecondOccurence + 1));
I'd suggest to modify your code as follows.
...
String[] itemID = line.split(",", 3); //attempt to use a regex limit
if(itemID[0].equals(test)) {
System.out.println(String.join (",", itemID[0],itemID[1]));
}
...
The split() call will produce an array with maximum 3 elements. First two will be the string pieces that you need. The last element is the remaining "tail" of the original string.
Now we only need to merge the pieces back with the join() method.
Hope this helps.

I need some guidance on the substring function in JAVA

I'm not sure where I am going wrong with this particular code. Could someone please lend me some guidance to this?
Here is my question as well as what I have attempted to have as an outcome.
Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.
Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints:
Banana-fana fo-fatie!
Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints:
Fee fi mo-matie
Note: You may assume songVerse will always contain the substring "(Name)".
Code that I tried this last time...and no matter what I put in I keep getting the same results. I've tried different scenarios of the "userName.substring()" and still have the same outcome.
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1 test passed
All tests passed
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
Here you go.
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}
}
here you removed first character already from userName, so at the second last line you again don't need to remove it.
and for the song Verse, you need to remove "(NAME)" from it, so here you can use
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
The method substring(int begin, int end) let hoose/create a substring from the initial String indicating the numbers of chars from which the substring should begin and end or begin only. There are no other variants to edit a substring, while it will not become a part of a freshly made string (“String songVerse” in your case). The object.replace() method should change the indicated “Text” (in your case it’s a “(Name)”) onto anything that you’d like to be inserted instead of it independently on the quantity or type of the chars before or after the “Text”. The variant proposed by Nicholas K is correct and should work or you can try its shorter version, however the result will be the same:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
The problem with your code is that you are not attempting to solve the problem that you described in your question.
Try following these steps:
Devise a list of steps written in English to solve the problem; pay attention to details.
Run the list of steps in step 1 by hand.
Convert the steps in step 1 to code.
Here are some hints:
You will be reading the lyrics one line at a time.
Some lines have a replacement and others do not.
You will receive the Name as input one time; generate the name replacement value one time and use it each time you perform a replacement.
Your code is terrible.
Here is some more about "Pay attention to details"
You do not have a loop in your code;
this will read one line of lyrics and perform one substitution.
Count the number of lines in the lyrics.
If the number of lines is greater than one,
then your technique is guaranteed to fail.
If you have a loop in your code but decided not to include it in your code,
stop lying in your questions.
We can not help you fix code that you pretend does not exist.
In a sane world,
the name to use for the substitutions will appear exactly one time.
Read it one time.
In order to replace (Name) in a string, you must first find (Name) in a string.
This is pretty easy
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName);
/* Your solution goes here */
System.out.println(songVerse);
}
}

IndexOf(), String index out of bounds: -1

I have no idea what is happening. I have a list of products along with a number separated with a tab. When I use indexOf() to find the tab, I get a String index out of bounds error, and it says the index is -1. Here's the code:
package taxes;
import java.util.*;
import java.io.*;
public class Taxes {
public static void main(String[] args) throws IOException {
//File aFile = new File("H:\\java\\PrimeNumbers\\build\\classes\\primenumbers\\priceList.txt");
File aFile = new File("C:\\Users\\Tim\\Documents\\NetBeansProjects\\Taxes\\src\\taxes\\priceList.txt");
priceChange(aFile);
}
static void priceChange(File inFile) throws IOException {
Scanner scan = new Scanner("priceList.txt");
char tab = '\t';
while (scan.hasNextLine()) {
String line = scan.nextLine();
int a = line.indexOf(tab);
String productName = line.substring(0,a);
String priceTag = line.substring(a);
}
}
}
And here's the input:
Plyer set 10
Jaw Locking Plyers 10
Cable Cutter 7
16 oz. Hammer 5
64 oz. Dead Blow Hammer 12
Sledge Hammer 20
Cordless Drill 22
Hex Impact Driver 50
Drill Bit Set 30
Miter Saw 200
Circular Saw 40
Scanner scan = new Scanner("priceList.txt");
This line of code is wrong. This Scanner instance will scan the String "priceList.txt". It doesn't contain a tab, therefore indexOf returns -1.
Change it to:
Scanner scan = new Scanner(inFile);
to use the method argument, that is the desired file instance of your priceList.txt.
String.indexOf(char) will return -1 if an instance isn't found.
You need to check before proceeding that a isn't negative.
You can read more about the indexOf method here and here.
Because you are checking int a = line.indexOf(tab) in every iteration of the while loop, there has to be a tab in every single line of your document in order for the error to be prevented.
When your while (scan.hasNextLine()) loop runs into a line with no tab in it, the index is going to be -1, and you get the StringIndexOutOfBoundsException when trying to get line.substring(0,a), with a being -1.
while (scan.hasNextLine()) {
String line = scan.nextLine();
int a = line.indexOf(tab);
if(a!=-1) {
String productName = line.substring(0,a);
String priceTag = line.substring(a);
}
}
If you look very carefully at the input lines you have posted, you'll see
Jaw Locking Plyers 10
...
Cordless Drill 22
Hex Impact Driver 50
Drill Bit Set 30
that the "Hex Impact Driver" line has the price two characters to the right of the one in the lines before and after. This is an indication that "50" does not start at a tab position whereas "10" is at such a position, the next after the one for "22" and "30".
The Q&A editor does preserve TABs, so your editor preserves them as well, and your program should be able to recognize a TAB in the input lines.
That said, a TAB entered by hand (!) is a very poor choice for a separator. As you have experienced, text file presentation doesn't show it. It would be much better to use a special character that does not occur in the product names. Plausible choices are '|', '#', and '\'.
Another good way would be to use pattern matching to find the numeric price at the end of a line - the product name is what remains after removing the price and calling trim() on the remaining string.
Since it has been verified that indexOf(tab) returns -1, the question is why does the line of text not contain t a tab when you seem certain that it does?
The answer is most likely the settings on your IDE. For instance, I usually configure Netbeans to convert a tab to three spaces. So if you typed this input file yourself within an IDE, the tab-to-space conversion is likely the problem.
Work around:
If we copy/paste some text into Netbeans that includes tabs, the tabs do not get converted to spaces.
The text file could be created with notepad or any other simple text editor to avoid the problem.
Change the settings on your IDE, at least for this project.

How do I print an array without the first term?

I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?
You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();
You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.

Novice programmer needs advice: "String index out of range" - Java

I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.
Here is what I have:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while ( line != null )
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
Basically, it finds the last name, first name and office number in a .csv file and prints them out.
When I compile I don't get any errors but when I run it I get:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.
Any ideas?
Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.
Let's work by example, what issues you have with your code.
Eg: line: Overflow,stack
{ length: 14 }
Taking your program statements line by line -
int positionOfComma = line.indexOf(","); // returns 9
lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1
Now lastName has Overflow. positionOfComma has 9.
line = line.substring(positionOfComma+1);
Now line has stack.
firstName = line.substring(0,positionOfComma);
Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.
From JavaDoc:
(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.
In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.
You need to:
a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)
b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.
A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)
You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.
int positionOfComma = line.indexOf(",");
this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:
int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
positionOfComma = line.indexOf(",");
}
You do have to do lots of checking of things sometimes especially when the data is whacked :(
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)

Categories

Resources