Search Results

Search found 102 results on 5 pages for 'replaceall'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Java replace all capturing groups

    - by Don
    Hi, If I have a regex with a capturing group, e.g. foo(g.*f). If I match this against a string and want to replace the first capturing group in all matches with baz so that foog___f blah foog________f is converted to: foobaz blah foobaz There doesn't appear to be any easy way to do this using the standard libraries, because the Matcher.replaceAll() method will only replace all matches of the entire pattern, am I missing something? Obviously I can just iterate through the matches, store the start and end index of each capturing group, then go back and replace them, but is there an easier way? Thanks, Don

    Read the article

  • Exception during processing XSLT transformation!

    - by Artic
    I'm using this code to generate contents file. try { StreamResult result = new StreamResult(); TransformerFactory tf = TransformerFactory.newInstance(); Templates templ = tf.newTemplates(xsltSource); Transformer transf = templ.newTransformer(); for (String item: groups){ item = item.replaceAll(" ", "-").toLowerCase(); result.setOutputStream(new FileOutputStream(path+item+".html")); transf.clearParameters(); transf.setParameter("group", item); transf.transform(xmlSource, result); } } catch (TransformerConfigurationException e) { throw new SinkException(e.getMessage()); } catch (TransformerException e) { throw new SinkException(e.getMessage()); } But on second iteration I have an exception ERROR: javax.xml.transform.TransformerException: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Read error Cann't understand what is the reason?

    Read the article

  • Trouble calling a method from an external class

    - by Bradley Hobbs
    Here is my employee database program: import java.util.*; import java.io.*; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class P { //Instance Variables private static String empName; private static String wage; private static double wages; private static double salary; private static double numHours; private static double increase; // static ArrayList<String> ARempName = new ArrayList<String>(); // static ArrayList<Double> ARwages = new ArrayList<Double>(); // static ArrayList<Double> ARsalary = new ArrayList<Double>(); static ArrayList<Employee> emp = new ArrayList<Employee>(); public static void main(String[] args) throws Exception { clearScreen(); printMenu(); question(); exit(); } public static void printArrayList(ArrayList<Employee> emp) { for (int i = 0; i < emp.size(); i++){ System.out.println(emp.get(i)); } } public static void clearScreen() { System.out.println("\u001b[H\u001b[2J"); } private static void exit() { System.exit(0); } private static void printMenu() { System.out.println("\t------------------------------------"); System.out.println("\t|Commands: n - New employee |"); System.out.println("\t| c - Compute paychecks |"); System.out.println("\t| r - Raise wages |"); System.out.println("\t| p - Print records |"); System.out.println("\t| d - Download data |"); System.out.println("\t| u - Upload data |"); System.out.println("\t| q - Quit |"); System.out.println("\t------------------------------------"); System.out.println(""); } public static void question() { System.out.print("Enter command: "); Scanner q = new Scanner(System.in); String input = q.nextLine(); input.replaceAll("\\s","").toLowerCase(); boolean valid = (input.equals("n") || input.equals("c") || input.equals("r") || input.equals("p") || input.equals("d") || input.equals("u") || input.equals("q")); if (!valid){ System.out.println("Command was not recognized; please try again."); printMenu(); question(); } else if (input.equals("n")){ System.out.print("Enter the name of new employee: "); Scanner stdin = new Scanner(System.in); empName = stdin.nextLine(); System.out.print("Hourly (h) or salaried (s): "); Scanner stdin2 = new Scanner(System.in); wage = stdin2.nextLine(); wage.replaceAll("\\s","").toLowerCase(); if (!(wage.equals("h") || wage.equals("s"))){ System.out.println("Input was not h or s; please try again"); } else if (wage.equals("h")){ System.out.print("Enter hourly wage: "); Scanner stdin4 = new Scanner(System.in); wages = stdin4.nextDouble(); Employee emp1 = new HourlyEmployee(empName, wages); emp.add(emp1); printMenu(); question();} else if (wage.equals("s")){ System.out.print("Enter annual salary: "); Scanner stdin5 = new Scanner(System.in); salary = stdin5.nextDouble(); Employee emp1 = new SalariedEmployee(empName, salary); printMenu(); question();}} else if (input.equals("c")){ for (int i = 0; i < emp.size(); i++){ System.out.println("Enter number of hours worked by " + emp.get(i) + ":"); } Scanner stdin = new Scanner(System.in); numHours = stdin.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); System.out.print("Enter number of hours worked by " + empName); Scanner stdin2 = new Scanner(System.in); numHours = stdin2.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); printMenu(); question();} else if (input.equals("r")){ System.out.print("Enter percentage increase: "); Scanner stdin = new Scanner(System.in); increase = stdin.nextDouble(); System.out.println("\nNew Wages"); System.out.println("---------"); // System.out.println(Employee.toString()); printMenu(); question(); } else if (input.equals("p")){ printArrayList(emp); printMenu(); question(); } else if (input.equals("q")){ exit(); } } } Here is one of the class files: public abstract class Employee { private String name; private double wage; protected Employee(String name, double wage){ this.name = name; this.wage = wage; } public String getName() { return name; } public double getWage() { return wage; } public void setName(String name) { this.name = name; } public void setWage(double wage) { this.wage = wage; } public void percent(double wage, double percent) { wage *= percent; } } And here are the errors: P.java:108: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ P.java:112: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ 2 errors I'm trying to the get paycheck to print out but i'm having trouble with how to call the method. It should take the user inputed numHours and calculate it then print on the paycheck for each employee. Thanks!

    Read the article

  • codingBat repeatEnd using regex

    - by polygenelubricants
    I'm trying to understand regex as much as I can, so I came up with this regex-based solution to codingbat.com repeatEnd: Given a string and an int N, return a string made of N repetitions of the last N characters of the string. You may assume that N is between 0 and the length of the string, inclusive. public String repeatEnd(String str, int N) { return str.replaceAll( ".(?!.{N})(?=.*(?<=(.{N})))|." .replace("N", Integer.toString(N)), "$1" ); } Explanation on its parts: .(?!.{N}): asserts that the matched character is one of the last N characters, by making sure that there aren't N characters following it. (?=.*(?<=(.{N}))): in which case, use lookforward to first go all the way to the end of the string, then a nested lookbehind to capture the last N characters into \1. Note that this assertion will always be true. |.: if the first assertion failed (i.e. there are at least N characters ahead) then match the character anyway; \1 would be empty. In either case, a character is always matched; replace it with \1. My questions are: Is this technique of nested assertions valid? (i.e. looking behind during a lookahead?) Is there a simpler regex-based solution?

    Read the article

  • Writing Russian in XML

    - by zavié
    Hi, I am writing a Xml Tag Renamer class with Java which reads in a XML, renames the tags and write them back into another XML file using DocumentBuilderFactory and TransformerFactory (text nodes are preserved). It worked fine before with German and English texts, until today, when I tried to rename a XML file with russian text. Instead of the source texts I got ????? in the newly created XML file. I've tried setting Encoding Any idea how to correct this? Thanks! PS. Strings were correct before entering TransformerFactory, as I checked in the debugger. I've tried setting OutputKeys.ENCODING to UTF-8 and ISO-8859-5. None of them helped. The Transformer part: // Output the XML // Set up a transformer TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // Fix to a bug about indent in transformer transformer.setOutputProperty ("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // TODO encoding parameter transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // Create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = sw.toString(); xmlString.replaceAll("\n", System.getProperty("line.separator")); // Write to file BufferedWriter output = new BufferedWriter(new FileWriter(outputPath)); output.write(xmlString); output.close();

    Read the article

  • Why is Swing Parser's handleText not handling nested tags?

    - by Jim P
    I need to transform some HTML text that has nested tags to decorate 'matches' with a css attribute to highlight it (like firefox search). I can't just do a simple replace (think if user searched for "img" for example), so I'm trying to just do the replace within the body text (not on tag attributes). I have a pretty straightforward HTML parser that I think should do this: final Pattern pat = Pattern.compile(srch, Pattern.CASE_INSENSITIVE); Matcher m = pat.matcher(output); if (m.find()) { final StringBuffer ret = new StringBuffer(output.length()+100); lastPos=0; try { new ParserDelegator().parse(new StringReader(output.toString()), new HTMLEditorKit.ParserCallback () { public void handleText(char[] data, int pos) { ret.append(output.subSequence(lastPos, pos)); Matcher m = pat.matcher(new String(data)); ret.append(m.replaceAll("<span class=\"search\">$0</span>")); lastPos=pos+data.length; } }, false); ret.append(output.subSequence(lastPos, output.length())); return ret; } catch (Exception e) { return output; } } return output; My problem is, when I debug this, the handleText is getting called with text that includes tags! It's like it's only going one level deep. Anyone know why? Is there some simple thing I need to do to HTMLParser (haven't used it much) to enable 'proper' behavior of nested tags? PS - I figured it out myself - see answer below. Short answer is, it works fine if you pass it HTML, not pre-escaped HTML. Doh! Hope this helps someone else. <span>example with <a href="#">nested</a> <p>more nesting</p> </span> <!-- all this gets thrown together -->

    Read the article

  • multiple keys and values with google-collections

    - by flash3000
    Hello, I would like use google-collection in order to save the following file in a Hash with multiple keys and values Key1_1, Key2_1, Key3_1, data1_1, 0, 0 Key1_2, Key2_2, Key3_2, data1_2, 0, 0 Key1_3, Key2_3, Key3_3, data1_3, 0, 0 Key1_4, Key2_4, Key3_4, data1_4, 0, 0 The first three columns are the different keys and the last two integer are the two different values. I have already prepare a code which spilt the lines in chunks. import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class HashMapKey { public static void main(String[] args) throws FileNotFoundException, IOException { String inputFile = "inputData.txt"; BufferedReader br = new BufferedReader(new FileReader(inputFile)); String strLine; while ((strLine = br.readLine()) != null) { String[] line = strLine.replaceAll(" ", "").trim().split(","); for (int i = 0; i < line.length; i++) { System.out.print("[" + line[i] + "]"); } System.out.println(); } } } Unfortunately, I do not know how to save these information in google-collection? Thank you in advance. Best regards,

    Read the article

  • Java UTF-8 to ASCII conversion with supplements

    - by bozo
    Hi, we are accepting all sorts of national characters in UTF-8 string on the input, and we need to convert them to ASCII string on the output for some legacy use. (we don't accept Chinese and Japanese chars, only European languages) We have a small utility to get rid of all the diacritics: public static final String toBaseCharacters(final String sText) { if (sText == null || sText.length() == 0) return sText; final char[] chars = sText.toCharArray(); final int iSize = chars.length; final StringBuilder sb = new StringBuilder(iSize); for (int i = 0; i < iSize; i++) { String sLetter = new String(new char[] { chars[i] }); sLetter = Normalizer.normalize(sLetter, Normalizer.Form.NFC); try { byte[] bLetter = sLetter.getBytes("UTF-8"); sb.append((char) bLetter[0]); } catch (UnsupportedEncodingException e) { } } return sb.toString(); } The question is how to replace all the german sharp s (ß, Ð, d) and other characters that get through the above normalization method, with their supplements (in case of ß, supplement would probably be "ss" and in case od Ð supplement would be either "D" or "Dj"). Is there some simple way to do it, without million of .replaceAll() calls? So for example: Ðonardan = Djonardan, Blaß = Blass and so on. We can replace all "problematic" chars with empty space, but would like to avoid this to make the output as similar to the input as possible. Thank you for your answers, Bozo

    Read the article

  • Algorithm to detect how many words typed, also multi sentence support (Java)

    - by Alex Cheng
    Hello all. Problem: I have to design an algorithm, which does the following for me: Say that I have a line (e.g.) alert tcp 192.168.1.1 (caret is currently here) The algorithm should process this line, and return a value of 4. I coded something for it, I know it's sloppy, but it works, partly. private int counter = 0; public void determineRuleActionRegion(String str, int index) { if (str.length() == 0 || str.indexOf(" ") == -1) { triggerSuggestionList(1); return; } //remove duplicate space, spaces in front and back before searching int num = str.trim().replaceAll(" +", " ").indexOf(" ", index); //Check for occurances of spaces, recursively if (num == -1) { //if there is no space //no need to check if it's 0 times it will assign to 1 triggerSuggestionList(counter + 1); counter = 0; return; //set to rule action } else { //there is a space counter++; determineRuleActionRegion(str, num + 1); } } //end of determineactionRegion() So basically I find for the space and determine the region (number of words typed). However, I want it to change upon the user pressing space bar <space character>. How may I go around with the current code? Or better yet, how would one suggest me to do it the correct way? I'm figuring out on BreakIterator for this case... To add to that, I believe my algorithm won't work for multi sentences. How should I address this problem as well. -- The source of String str is acquired from textPane.getText(0, pos + 1);, the JTextPane. Thanks in advance. Do let me know if my question is still not specific enough.

    Read the article

  • Using java.util.regex in Android apps - are there issues with this?

    - by johnrock
    In an Android app I have a utility class that I use to parse strings for 2 regEx's. I compile the 2 patterns in a static initializer so they only get compiled once, then activities can use the parsing methods statically. This works fine except that the first time the class is accessed and loaded, and the static initializer compiles the pattern, the UI hangs for close to a MINUTE while it compiles the pattern! After the first time, it flies on all subsequent calls to parseString(). My regEx that I am using is rather large - 847 characters, but in a normal java webapp this is lightning fast. I am testing this so far only in the emulator with a 1.5 AVD. Could this just be an emulator issue or is there some other reason that this pattern is taking so long to compile? private static final String exp1 = "(insertratherlong---847character--regexhere)"; private static Pattern regex1 = null; private static final String newLineAndTagsExp = "[<>\\s]"; private static Pattern regexNewLineAndTags = null; static { regex1 = Pattern.compile(exp1, Pattern.CASE_INSENSITIVE); regexNewLineAndTags = Pattern.compile(newLineAndTagsExp); } public static String parseString(CharSequence inputStr) { String replacementStr = "replaceMentText"; String resultString = "none"; try { Matcher regexMatcher = regex1.matcher(inputStr); try { resultString = regexMatcher.replaceAll(replacementStr); } catch (IllegalArgumentException ex) { } catch (IndexOutOfBoundsException ex) { } } catch (PatternSyntaxException ex) { } return resultString; }

    Read the article

  • How to replace characters in a java String?

    - by ManBugra
    I like to replace a certain set of characters of a string with a corresponding replacement character in an efficent way. For example: String sourceCharacters = "šdccŠÐCCžŽ"; String targetCharacters = "sdccSDCCzZ"; String result = replaceChars("Gracišce", sourceCharacters , targetCharacters ); Assert.equals(result,"Gracisce") == true; Is there are more efficient way than to use the replaceAll method of the String class? My first idea was: final String s = "Gracišce"; String sourceCharacters = "šdccŠÐCCžŽ"; String targetCharacters = "sdccSDCCzZ"; // preparation final char[] sourceString = s.toCharArray(); final char result[] = new char[sourceString.length]; final char[] targetCharactersArray = targetCharacters.toCharArray(); // main work for(int i=0,l=sourceString.length;i<l;++i) { final int pos = sourceCharacters.indexOf(sourceString[i]); result[i] = pos!=-1 ? targetCharactersArray[pos] : sourceString[i]; } // result String resultString = new String(result); Any ideas? Btw, the UTF-8 characters are causing the trouble, with US_ASCII it works fine.

    Read the article

  • exec() in BeanShell macro causes jEdit to hang when it returns non-zero exit code

    - by rossmeissl
    I have a jEdit BeanShell macro that runs my Markdown files through Maruku when I save them: if (buffer.getMode().toString().equals("markdown")) { cmd = "C:\\Ruby\\bin\\maruku.bat -o " + buffer.getDirectory() + buffer.getName().replaceAll("markdown$", "html") + " " + buffer.getPath(); exec(cmd); } This works great when the Markdown file is valid. But if I've made a mistake, jEdit just waits around forever for the exec() call to "succeed," which it never will. When this happens, I have to kill jEdit's javaw.exe process and run Maruku manually from the command line to discover the error, e.g.: E:\bp\plan\supply_chain>maruku business_plan.markdown ___________________________________________________________________________ | Maruku tells you: +--------------------------------------------------------------------------- | Could not find ref_id = "17" for md_link(["17"],"17") | Available refs are [] +--------------------------------------------------------------------------- !C:/Ruby/lib/ruby/gems/1.8/gems/maruku-0.6.0/lib/maruku/errors_management.rb:49:in `maruku_error' !C:/Ruby/lib/ruby/gems/1.8/gems/maruku-0.6.0/lib/maruku/output/to_html.rb:716:in `to_html_link' !C:/Ruby/lib/ruby/gems/1.8/gems/maruku-0.6.0/lib/maruku/output/to_html.rb:970:in `send' !C:/Ruby/lib/ruby/gems/1.8/gems/maruku-0.6.0/lib/maruku/output/to_html.rb:970:in `array_to_html' !C:/Ruby/lib/ruby/gems/1.8/gems/maruku-0.6.0/lib/maruku/output/to_html.rb:961:in `each' \___________________________________________________________________________ Not creating a link for ref_id = "17". Then I restart jEdit, fix the error, and re-save the file, at which point the macro succeeds. How can I make my macro more resilient to either die helpfully (display Maruku's error output) or, at the very least, die silently so I don't have to kill jEdit?

    Read the article

  • Translation of a RoR view to Java

    - by mnml
    Hi, for some reasons I am trying to translate the following RoR view code to a GSP view: List<Object> objectscontains the data I want to display in 3 columns <% modulo_objects = @objects.length % 3 base = @objects.length / 3 base = base.ceil case modulo_objects when 0 cols = [base, base, base] when 1 cols = [base, base + 1, base] when 2 cols = [base + 1, base, base + 1] end counter = 0 %> <% 3.times do |i| %> <td width="220" align="center" style="padding-right: 15px;"> <% cols[i].times do %> <h1><a href="/objects/show/<%= @objects[counter].urlname %>" ><%= @objects[counter].name %></a></h1> <% counter = counter + 1 %> <% end %> </td> <% end %> This is what I got so far: #{extends 'main.html' /} %{ modulo_objects = objects.size() % 3 base = objects.size() / 3 base = Math.ceil(base) if(modulo_objects == 0) cols = [base, base, base] else if(modulo_objects == 1) cols = [base, base + 1, base] else if(modulo_objects == 2) cols = [base + 1, base, base + 1] endif counter = 0 }% #{list items:1..3, as:'i'} <td width="220" align="center" style="padding-right: 15px;"> #{list items:cols[i]} <a href="@{Objects.show(objects.get(counter).name.replaceAll(" ", "-"))}" >${objects.get(counter).name}</a> %{ counter = counter + 1 }% #{/list} </td> #{/list} The idea is to keep the items organised in 3 columns like 1|0|1 4|5|4 or 5|4|5 for example, I don't really understand if #{list items:cols[i]} will reproduce ruby's cols[i].times do. So far the Java view is does not display more than two elements.

    Read the article

  • User will input some filter criteria -- how can I turn it into a regular expression for String.match

    - by envinyater
    I have a program where the user will enter a string such as PropertyA = "abc_*" and I need to have the asterisk match any character. In my code, I'm grabbing the property value and replacing PropertyA with the actual value. For instance, it could be abc_123. I also pull out the equality symbol into a variable. It should be able to cover this type of criteria PropertyB = 'cba' PropertyC != '*-this' valueFromHeader is the lefthand side and value is the righthand side. if (equality.equals("=")) { result = valueFromHeader.matches(value); } else if (equality.equals("!=")) { result = !valueFromHeader.matches(value); } EDIT: The existing code had this type of replacement for regular expressions final String ESC = "\\$1"; final String NON_ALPHA = "([^A-Za-z0-9@])"; final String WILD = "*"; final String WILD_RE_TEMP = "@"; final String WILD_RE = ".*"; value = value.replace(WILD, WILD_RE_TEMP); value = value.replaceAll(NON_ALPHA,ESC); value = value.replace(WILD_RE_TEMP, WILD_RE); It doesn't like the underscore here... abcSite_123 != abcSite_123 (evaluates to true) abcSite_123$1.matches("abcSite$1123") It doesn't like the underscore...

    Read the article

  • Replacing characters in a non well-formed XML body

    - by ryanprayogo
    In a (Java) code that I'm working on, I sometimes deal with a non well-formed XML (represented as a Java String), such as: <root> <foo> bar & baz < quux </foo> </root> Since this XML will eventually need to be unmarshalled (using JAXB), obviously this XML as is will throw exception upon unmarshalling. What's the best way to replace the & and the < to its character entities? For &, it's as easy as: xml.replaceAll("&", "&amp;") However, for the < symbol, it's a bit tricky since obviously I don't want to replace the < that's used for the XML tag opening 'bracket'. Other than scanning the string and manually replacing < in the XML body with &lt;, what other option can you suggest?

    Read the article

  • need to clean malformed tags using regular expression

    - by Brian
    Looking to find the appropriate regular expression for the following conditions: I need to clean certain tags within free flowing text. For example, within the text I have two important tags: <2004:04:12 and . Unfortunately some of tags have missing "<" or "" delimiter. For example, some are as follows: 1) <2004:04:12 , I need this to be <2004:04:12> 2) 2004:04:12>, I need this to be <2004:04:12> 3) <John Doe , I need this to be <John Doe> I attempted to use the following for situation 1: String regex = "<\\d{4}-\\d{2}-\\d{2}\\w*{2}[^>]"; String output = content.replaceAll(regex,"$0>"); This did find all instances of "<2004:04:12" and the result was "<2004:04:12 ". However, I need to eliminate the space prior to the ending tag. Not sure this is the best way. Any suggestions. Thanks

    Read the article

  • Word Automation : Replace do not work after TypeText

    - by wishper
    I need to generate doc (real doc, not docx) files, the "best" way i have found is to use word automation (Word 2010). I have files that I open, and then replace values inside before saving it on a new name. (Ex : I replace "" with "155023"). To do this, I use the Application.Selection.Find. I just had a problem when the new value had more than 255 characters (Thanks Microsofts limitations ...). To avoid this problem, i use TypeText in this case. My problem now is once I use TypeText, the Replace do not work anymore .. And I can't find why. Any idea will be greatly appreciated. My code is in a function, called in a foreach with each values to replace : private void Replace(Application app, string name, string newValue) { Selection selection = app.Selection; Find find = selection.Find; Replacement replacement = find.Replacement; find.ClearFormatting(); find.Text = "<" + name + ">"; // Word limitation : can't replace with more than 255 characters, // use another way to do it if that's the case if (tempNewValue.Length < 255) { replacement.ClearFormatting(); replacement.Text = tempNewValue; find.Execute(Replace: replaceAll); } else { while (find.Execute()) { selection.TypeText(tempNewValue); } } Marshal.ReleaseComObject(replacement); Marshal.ReleaseComObject(find); Marshal.ReleaseComObject(selection); }

    Read the article

  • one more time about loop that doesn't work

    - by unit
    I have asked a couple of questions about this for loop: String[] book = new String [ISBN_NUM]; bookNum.replaceAll("-",""); if (bookNum.length()!=ISBN_NUM) throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters"); for (int i=0;i<bookNum.length();i++) { if (Character.isDigit(bookNum.charAt(i))) book[j]=bookNum.charAt(i); //this is the problem right here j++; if (book[9].isNotDigit()|| book[9]!="x" || book[9]!="X") throw new ISBNException ("ISBN " + bookNum + " must contain all digits" + "or 'X' in the last position"); } which will not compile. An answer I had from the other question I asked told me that the line where the error occurs is wrong in that bookNum.charAt(i) is an (immutable) string, and I can't get the values into a book array that way. What I need to do on my assignment is check an ISBN number (bookNum) to see that it is all numbers, except the last digit can be an 'x' (valid ISBN). Is this the best way to do it? If so, what the hell am I doing wrong? If not, what method would be a better one to use?

    Read the article

  • Java: I've created a list of word objects to include the name and the frequency, but having trouble

    - by adam08
    Hi Everyone, I'm working on a project which has a dictionary of words and I'm extracting them and adding them to an ArrayList as word objects. I have a class called Word as below. What I'm wondering is how do I access these word objects to update the frequency? As part of this project, I need to only have one unique word, and increase the frequency of that word by the number of occurrences in the dictionary. Word(String word) { this.word = word; this.freq = 0; } public String getWord() { return word; } public int getFreq() { return freq; } public void setFreq() { freq = freq + 1; } This is how I am adding the word objects to the ArrayList...I think it's ok? String pattern = "[^a-zA-Z\\s]"; String strippedString = line.replaceAll(pattern, ""); line = strippedString.toLowerCase(); StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { String newWord = st.nextToken(); word.add(new Word(newWord)); count++; }

    Read the article

  • I asked a question about arrays before, but this one won't compile

    - by unit
    I asked about this array a little while ago, and I can't see what the problem is. Too tired. What have I done wrong? Basically, I am taking a string array and trying to check to see if it contains numbers or an x (ISBN number validation). I want to take the number from a given input (bookNum), check the input, and feed any valid input into a new array (book). At the line 'bookNum.charAt[j]==book[i]' I get the 'not a statement error'. What gives? String[] book = new String [ISBN_NUM]; bookNum.replaceAll("-",""); if (bookNum.length()!=ISBN_NUM) throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters"); for (int i=0;i<bookNum.length();i++) { if (Character.isDigit(bookNum.charAt(i))) bookNum.CharAt[j]==book[i]; j++; if (book[9].isNotDigit()|| book[9]!="x" || book[9]!="X") throw new ISBNException ("ISBN " + bookNum + " must contain all digits" + "or 'X' in the last position");

    Read the article

  • Translate RoR Code to Java

    - by mnml
    Hi, for some reasons I am trying to translate the following RoR view code to a Java Groovy view: <% modulo_artists = @artists.length % 3 base = @artists.length / 3 base = base.ceil case modulo_artists when 0 cols = [base, base, base] when 1 cols = [base, base + 1, base] when 2 cols = [base + 1, base, base + 1] end counter = 0 %> <% id_hash = {"0" => "url('/images/actorsbg.png');", "1" => "url('/images/musiciansbg.png');", "2" => "url('/images/artistsbg.png') no-repeat; color: #FFF;", "3" => "url('/images/fashionbg.png')"} %> <div id="artists_<%=params[:artist_cat]%>" style="background: <%= id_hash[params[:artist_cat]] %>;" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> <% 3.times do |i| %> <td width="220" align="center" style="padding-right: 15px;"> <% cols[i].times do %> <h1><a href="/artists/show/<%= @artists[counter].urlname %>" ><%= @artists[counter].name %></a></h1> <% counter = counter + 1 %> <% end %> </td> <% end %> </tr> </table> </div> This is what I got so far: #{extends 'main.html' /} %{ modulo_artists = artists.size() % 3 base = artists.size() / 3 base = Math.ceil(base) if(modulo_artists == 0) cols = [base, base, base] else if(modulo_artists == 1) cols = [base, base + 1, base] else if(modulo_artists == 2) cols = [base + 1, base, base + 1] endif counter = 0 }% <div id="artists_${artist_cat}" style="background:${id_hash};" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> #{list items:1..3, as:'i'} <td width="220" align="center" style="padding-right: 15px;"> #{list items:cols[i]} <h1><a href="@{Artists.show(artists.get(counter).name.replaceAll(" ", "-"))}" >${artists.get(counter).name}</a></h1> %{ counter = counter + 1 }% #{/list} </td> #{/list} </tr> </table> </div> The idea is to keep the items organised in 3 columns like 1|0|1 4|5|4 or 5|4|5 for example

    Read the article

  • I would like to run my Java program on System Startup on Mac OS/Windows. How can I do this?

    - by Misha Koshelev
    Here is what I came up with. It works but I was wondering if there is something more elegant. Thank you! Misha package com.mksoft.fbbday; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; public class RunOnStartup { public static void install(String className,boolean doInstall) throws IOException,URISyntaxException { String osName=System.getProperty("os.name"); String fileSeparator=System.getProperty("file.separator"); String javaHome=System.getProperty("java.home"); String userHome=System.getProperty("user.home"); File jarFile=new File(RunOnStartup.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (osName.startsWith("Windows")) { Process process=Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v Startup"); BufferedReader in=new BufferedReader(new InputStreamReader(process.getInputStream())); String result="",line; while ((line=in.readLine())!=null) { result+=line; } in.close(); result=result.replaceAll(".*REG_SZ[ ]*",""); File startupFile=new File(result+fileSeparator+jarFile.getName().replaceFirst(".jar",".bat")); if (doInstall) { PrintWriter out=new PrintWriter(new FileWriter(startupFile)); out.println("@echo off"); out.println("start /min \"\" \""+javaHome+fileSeparator+"bin"+fileSeparator+"java.exe -cp "+jarFile+" "+className+"\""); out.close(); } else { if (startupFile.exists()) { startupFile.delete(); } } } else if (osName.startsWith("Mac OS")) { File startupFile=new File(userHome+"/Library/LaunchAgents/com.mksoft."+jarFile.getName().replaceFirst(".jar",".plist")); if (doInstall) { PrintWriter out=new PrintWriter(new FileWriter(startupFile)); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" Label"); out.println(" com.mksoft."+jarFile.getName().replaceFirst(".jar","")+""); out.println(" ProgramArguments"); out.println(" "); out.println(" "+javaHome+fileSeparator+"bin"+fileSeparator+"java"); out.println(" -cp"); out.println(" "+jarFile+""); out.println(" "+className+""); out.println(" "); out.println(" RunAtLoad"); out.println(" "); out.println(""); out.println(""); out.close(); } else { if (startupFile.exists()) { startupFile.delete(); } } } } }

    Read the article

  • Given an XML which contains a representation of a graph, how to apply it DFS algorithm? [on hold]

    - by winston smith
    Given the followin XML which is a directed graph: <?xml version="1.0" encoding="iso-8859-1" ?> <!DOCTYPE graph PUBLIC "-//FC//DTD red//EN" "../dtd/graph.dtd"> <graph direct="1"> <vertex label="V0"/> <vertex label="V1"/> <vertex label="V2"/> <vertex label="V3"/> <vertex label="V4"/> <vertex label="V5"/> <edge source="V0" target="V1" weight="1"/> <edge source="V0" target="V4" weight="1"/> <edge source="V5" target="V2" weight="1"/> <edge source="V5" target="V4" weight="1"/> <edge source="V1" target="V2" weight="1"/> <edge source="V1" target="V3" weight="1"/> <edge source="V1" target="V4" weight="1"/> <edge source="V2" target="V3" weight="1"/> </graph> With this classes i parsed the graph and give it an adjacency list representation: import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.Collection; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import practica3.util.Disc; public class ParsingXML { public static void main(String[] args) { try { // TODO code application logic here Collection<Vertex> sources = new HashSet<Vertex>(); LinkedList<String> lines = Disc.readFile("xml/directed.xml"); for (String lin : lines) { int i = Disc.find(lin, "source=\""); String data = ""; if (i > 0 && i < lin.length()) { while (lin.charAt(i + 1) != '"') { data += lin.charAt(i + 1); i++; } Vertex v = new Vertex(); v.setName(data); v.setAdy(new HashSet<Vertex>()); sources.add(v); } } Iterator it = sources.iterator(); while (it.hasNext()) { Vertex ver = (Vertex) it.next(); Collection<Vertex> adyacencias = ver.getAdy(); LinkedList<String> ls = Disc.readFile("xml/graphs.xml"); for (String lin : ls) { int i = Disc.find(lin, "target=\""); String data = ""; if (lin.contains("source=\""+ver.getName())) { Vertex v = new Vertex(); if (i > 0 && i < lin.length()) { while (lin.charAt(i + 1) != '"') { data += lin.charAt(i + 1); i++; } v.setName(data); } i = Disc.find(lin, "weight=\""); data = ""; if (i > 0 && i < lin.length()) { while (lin.charAt(i + 1) != '"') { data += lin.charAt(i + 1); i++; } v.setWeight(Integer.parseInt(data)); } if (v.getName() != null) { adyacencias.add(v); } } } } for (Vertex vert : sources) { System.out.println(vert); System.out.println("adyacencias: " + vert.getAdy()); } } catch (IOException ex) { Logger.getLogger(ParsingXML.class.getName()).log(Level.SEVERE, null, ex); } } } This is another class: import java.util.Collection; import java.util.Objects; public class Vertex { private String name; private int weight; private Collection ady; public Collection getAdy() { return ady; } public void setAdy(Collection adyacencias) { this.ady = adyacencias; } public String getName() { return name; } public void setName(String nombre) { this.name = nombre; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } @Override public int hashCode() { int hash = 7; hash = 43 * hash + Objects.hashCode(this.name); hash = 43 * hash + this.weight; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vertex other = (Vertex) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (this.weight != other.weight) { return false; } return true; } @Override public String toString() { return "Vertice{" + "name=" + name + ", weight=" + weight + '}'; } } And finally: /** * * @author user */ /* -*-jde-*- */ /* <Disc.java> Contains the main argument*/ import java.io.*; import java.util.LinkedList; /** * Lectura y escritura de archivos en listas de cadenas * Ideal para el uso de las clases para gráficas. * * @author Peralta Santa Anna Victor Miguel * @since Julio 2011 */ public class Disc { /** * Metodo para lectura de un archivo * * @param fileName archivo que se va a leer * @return El archivo en representacion de lista de cadenas */ public static LinkedList<String> readFile(String fileName) throws IOException { BufferedReader file = new BufferedReader(new FileReader(fileName)); LinkedList<String> textlist = new LinkedList<String>(); while (file.ready()) { textlist.add(file.readLine().trim()); } file.close(); /* for(String linea:textlist){ if(linea.contains("source")){ //String generado = linea.replaceAll("<\\w+\\s+\"", ""); //System.out.println(generado); } }*/ return textlist; }//readFile public static int find(String linea,String palabra){ int i,j; boolean found = false; for(i=0,j=0;i<linea.length();i++){ if(linea.charAt(i)==palabra.charAt(j)){ j++; if(j==palabra.length()){ found = true; return i; } }else{ continue; } } if(!found){ i= -1; } return i; } /** * Metodo para la escritura de un archivo * * @param fileName archivo que se va a escribir * @param tofile la lista de cadenas que quedaran en el archivo * @param append el bit que dira si se anexa el contenido o se empieza de cero */ public static void writeFile(String fileName, LinkedList<String> tofile, boolean append) throws IOException { FileWriter file = new FileWriter(fileName, append); for (int i = 0; i < tofile.size(); i++) { file.write(tofile.get(i) + "\n"); } file.close(); }//writeFile /** * Metodo para escritura de un archivo * @param msg archivo que se va a escribir * @param tofile la cadena que quedaran en el archivo * @param append el bit que dira si se anexa el contenido o se empieza de cero */ public static void writeFile(String msg, String tofile, boolean append) throws IOException { FileWriter file = new FileWriter(msg, append); file.write(tofile); file.close(); }//writeFile }// I'm stuck on what can be the best way to given an adjacency list representation of the graph how to apply it Depth-first search algorithm. Any idea of how to aproach to complete the task?

    Read the article

  • How to code a time delay between plotting points in JFreeCharts?

    - by Javajava
    Is there a way to animate the plotting process of an xy-line chart using JFreeCharts? I want to be able to watch the program draw each line segment and connect them. For example, if I paste this into the TextArea, "gtgtaaacaatatatggcg," I want to watch it graph each line segment one by one. Thanks in advance! :) My code is below: import java.util.Scanner; import java.applet.Applet; import java.awt.; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import org.jfree.chart.; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.*; public class RandomWalkComplete extends Applet implements ActionListener { Panel panel; TextArea textarea, outputArea; Button move,exit; String thetext; Scanner reader = new Scanner(System.in); String thetext2; Label instructions; int x,y; public void init() { setSize(500,250); //set size of applet instructions=new Label("Paste the gene sequences in the " + "text field and press the graph button."); add(instructions); panel = new Panel(); add(panel); setVisible(true); textarea= new TextArea(10,20); add(textarea); move=new Button("Graph"); move.addActionListener(this); add(move); exit=new Button("Exit"); exit.addActionListener(this); add(exit); } public void actionPerformed(ActionEvent e) { XYSeries series = new XYSeries("DNA Walk",false,true); x= 0; y = 0; series.add(x,y); if(e.getSource() == move) { thetext=textarea.getText(); //the text is the DNA bases pasted thetext=thetext.replaceAll(" ",""); //removes spaces thetext2 = ""; for(int i=0; i<thetext.length(); i++) { char a = thetext.charAt(i); switch (a) { case 'A': case 'a'://moves right x+=1; y+=0; series.add(x,y); break; case 'C': case 'c': //moves up x+=0; y+=1; series.add(x,y); break; case 'G': case 'g': //move left x-=1; y+=0; series.add(x,y); break; case 'T': case 't'://move down x+=0; y-=1; series.add(x,y); break; default: // series.add(0,0); break; } } XYDataset xyDataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYLineChart ("DNA Random Walk", "", "", xyDataset, PlotOrientation.VERTICAL, true, true, false); ChartFrame frame1=new ChartFrame("DNA Random Walk",chart); frame1.setVisible(true); frame1.setSize(300,300); } if(e.getSource()==exit) {System.exit(0);} } public void stop(){} }

    Read the article

  • Runtime error on UVa Online Judge on Erdos Number

    - by 2012 - End of the World
    I am solving the Erdos number problem from the programming challenges in JAVA. The code runs perfectly in my machine. However on the online judge it results in a runtime error. Could anyone point out the mistake i made? http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=985 Here is the code import java.util.*; import java.io.*; class Main { private String inputLines[]; private String namesToBeFound[]; private String namesInEachBook[][]; private String searchItem; private boolean solnfound=false; private static final BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); static String read() throws IOException { String line; while(true) { line=br.readLine(); if(line==null) break; //eof else if(line.length()==0) continue; //blank line else { line=line.trim().replaceAll("\\s+"," "); return line; } } return null; } public static void main(String args[]) throws IOException { Main ob=new Main(); int totalPapers,calcAuthors,totalScenarios; //First input number of scenarios totalScenarios=Integer.parseInt(read()); //Now start a loop for reading total number of scenarios for(int scenario=1;scenario<=totalScenarios;scenario++) { //Now read the line containing the number of papers and authors StringTokenizer line=new StringTokenizer(read()," "); totalPapers=Integer.parseInt(line.nextToken()); calcAuthors=Integer.parseInt(line.nextToken()); //Read a line containing author names along with book names ob.inputLines=new String[totalPapers]; for(int i=0;i<totalPapers;i++) ob.inputLines[i]=read(); //Read a line containing the names to be searched ob.namesToBeFound=new String[calcAuthors]; for(int i=0;i<calcAuthors;i++) ob.namesToBeFound[i]=read(); //Now generate the array ob.buildArray(); //Now search System.out.println("Scenario "+scenario); for(int i=0;i<calcAuthors;i++) { ob.searchItem=ob.namesToBeFound[i]; if(ob.searchItem.equals("Erdos, P.")) { System.out.println("Erdos, P. 0"); continue; } ob.search(ob.namesToBeFound[i],1,new ArrayList()); if(ob.solnfound==false) System.out.println(ob.searchItem+" infinity"); ob.solnfound=false; } } } private void buildArray() { String str; namesInEachBook=new String[inputLines.length][]; for(int i=0;i<inputLines.length;i++) { str=inputLines[i]; str=str.substring(0,str.indexOf(':')); str+=","; namesInEachBook[i]=new String[(countCommas(str)+1)>>1]; for(int j=0;j<namesInEachBook[i].length;j++) { str=str.trim(); namesInEachBook[i][j]=""; namesInEachBook[i][j]+=str.substring(0,str.indexOf(','))+","; str=str.substring(str.indexOf(',')+1); namesInEachBook[i][j]+=str.substring(0,str.indexOf(',')); str=str.substring(str.indexOf(',')+1); } } } private int countCommas(String s) { int num=0; for(int i=0;i<s.length();i++) if(s.charAt(i)==',') num++; return num; } private void search(String searchElem,int ernosDepth,ArrayList searchedElem) { ArrayList searchSpace=new ArrayList(); searchedElem.add(searchElem); for(int i=0;i<namesInEachBook.length;i++) for(int j=0;j<namesInEachBook[i].length;j++) { if(namesInEachBook[i][j].equals(searchElem)) //Add all authors name in this group { for(int k=0;k<namesInEachBook[i].length;k++) { if(namesInEachBook[i][k].equals("Erdos, P.")) //Found { solnfound=true; System.out.println(searchItem+" "+ernosDepth); return; } else if(searchedElem.contains(namesInEachBook[i][k]) || searchSpace.contains(namesInEachBook[i][k])) continue; searchSpace.add(namesInEachBook[i][k]); } break; } } Iterator i=searchSpace.iterator(); while(i.hasNext()) { String cSearchElem=(String)i.next(); search(cSearchElem,ernosDepth+1,searchedElem); } } }

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >