public static boolean isFormat(String str, String... format) { if (str.length() == 0) return format.length == 1 && format[0].equals(""); char[] charset = str.toCharArray(); int c = 0; for (int i = 0; i < format.length; i++) { String form = format[i]; if (form.equals(NUMBERS)) { if (c >= charset.length) return false; if (!Character.isDigit(charset[c])) { if (charset[c] == '.') { if (c + 1 >= charset.length || !Character.isDigit(charset[c + 1])) return false; } else return false; } while (c < charset.length - 1 && (Character.isDigit(charset[c + 1]) || charset[c + 1] == '.')) c++; c++; } else if (form.equals(LETTERS)) { if (c >= charset.length || !Character.isLetter(charset[c])) return false; while (c < charset.length - 1 && Character.isLetter(charset[c + 1])) c++; c++; } else { char[] formchars = form.toCharArray(); if (formchars.length > charset.length - c) return false; for (int ch = 0; ch < formchars.length; ch++) { if (formchars[ch] != charset[c]) return false; c++; } } } return c == charset.length; }
/** * Modtager værtens svar, der godt kan løbe over flere linjer. Sidste linje er en svarkode på tre * cifre, uden en bindestreg '-' på plads nummer 4 */ private String læsSvar() throws IOException { while (true) { String s = ind.readLine(); System.out.println("modt: " + s); if (s.length() >= 3 && s.charAt(3) != '-' && Character.isDigit(s.charAt(0)) && Character.isDigit(s.charAt(1)) && Character.isDigit(s.charAt(2))) return s; // afslut løkken og returner sidste linje med statuskode } }
static int nextInt() throws IOException { int ch = -1; do { ch = System.in.read(); } while (!Character.isDigit(ch)); int ret = 0; while (Character.isDigit(ch)) { ret *= 10; ret += Character.digit(ch, 10); ch = System.in.read(); } return ret; }
/** * Parses the predicate definitions from the CSV file. * * @param csvFile The buffered reader containing the contents of the CSV file we are trying parse. * @param ds The destination datastore for the csv file. * @return The next line to be parsed from the file. * @throws IOException If unable to read from the csvFile. */ private String parseDefinitions(final BufferedReader csvFile, final Datastore db) throws IOException { // Keep parsing lines and putting them in the newly formed nominal // variable until we get to a line indicating the end of file or a new // variable section. String line = csvFile.readLine(); while ((line != null) && Character.isDigit(line.charAt(0))) { /* * TODO Parsing predicates. * // Parse arguments - for predicate vocab element. String[] token = line.split(":|(?<!\\\\)-"); PredicateVocabElement pve = new PredicateVocabElement(db, this.stripEscChars(token[1])); for (String arg : token[2].split(",")) { pve.appendFormalArg(parseFormalArgument(arg, db)); } db.addPredVE(pve); */ // Get the next line in the file for reading. line = csvFile.readLine(); } return line; }
static ReferenceType getReferenceTypeFromToken(String idToken) { ReferenceType cls = null; if (Character.isDigit(idToken.charAt(0))) { cls = null; } else if (idToken.startsWith("*.")) { // This notation saves typing by letting the user omit leading // package names. The first // loaded class whose name matches this limited regular // expression is selected. idToken = idToken.substring(1); for (ReferenceType type : Env.vm().allClasses()) { if (type.name().endsWith(idToken)) { cls = type; break; } } } else { // It's a class name List<ReferenceType> classes = Env.vm().classesByName(idToken); if (classes.size() > 0) { // TO DO: handle multiples cls = classes.get(0); } } return cls; }
public static String getDigits(String s) { String str = ""; for (int i = 0; i < s.length(); i++) { if (Character.isDigit(s.charAt(i))) str += s.charAt(i); } return str; }
public StringBuffer translate() { for (index = 0; index < line.length(); index++) { char c = line.charAt(index); if (Character.isDigit(c)) { dealWithOperand(); } else if (isOperator(c)) { dealWithOperator(c); } else if (c == '(') { stack.push(new Character(c)); } else if (c == ')') { dealWithCloser(); } else if (Character.isSpaceChar(c)) { // do nothing } else { System.out.println("Error: unknown character" + c); } } // pop and output all the operators left on the stack while (!stack.empty()) { out.append(popChar()); } return out; }
public Operand getOperand() { if (Character.isDigit(nextNonBlank())) { return new Real(getDouble()); } else { return new Variable(getName()); } }
/** Loads custom hyphenation rules. You probably want to use loadDefault() instead. */ public void load(BufferedReader input) throws IOException { String line; while ((line = input.readLine()) != null) { if (StringUtils.matches(line, "\\s*(%.*)?")) { // comment or blank line System.err.println("Skipping: " + line); continue; } char[] linechars = line.toCharArray(); int[] pattern = new int[linechars.length]; char[] chars = new char[linechars.length]; int c = 0; for (int i = 0; i < linechars.length; ++i) { if (Character.isDigit(linechars[i])) { pattern[c] = Character.digit(linechars[i], 10); } else { chars[c++] = linechars[i]; } } char[] shortchars = new char[c]; int[] shortpattern = new int[c + 1]; System.arraycopy(chars, 0, shortchars, 0, c); System.arraycopy(pattern, 0, shortpattern, 0, c + 1); insertHyphPattern(shortchars, shortpattern); } }
/** * Method to invoke when we encounter a block of text in the CSV file that is the contents of a * predicate variable. * * @param csvFile The csvFile we are currently parsing. * @param var The variable that we will be adding cells too. * @param arg The matrix template we are using when parsing individual matrix elements to put in * the spreadsheet. * @return The next line in the file that is not part of the block of text in the CSV file. * @throws IOException If unable to read the file correctly. */ private String parseMatrixVariable( final BufferedReader csvFile, final Variable var, final Argument arg) throws IOException { String line = csvFile.readLine(); while ((line != null) && Character.isDigit(line.charAt(0))) { // Split the line into tokens using a comma delimiter. String[] tokens = line.split(","); Cell newCell = var.createCell(); // Set the onset and offset from tokens in the line. newCell.setOnset(tokens[DATA_ONSET]); newCell.setOffset(tokens[DATA_OFFSET]); // Strip the brackets from the first and last argument. tokens[DATA_INDEX] = tokens[DATA_INDEX].substring(1, tokens[DATA_INDEX].length()); int end = tokens.length - 1; tokens[end] = tokens[end].substring(0, tokens[end].length() - 1); parseFormalArgs(tokens, DATA_INDEX, var.getVariableType(), (MatrixValue) newCell.getValue()); // Get the next line in the file for reading. line = csvFile.readLine(); } return line; }
// Retrieves a number from input string public double getDouble() { String s = ""; if (nextNonBlank() == '-' || nextNonBlank() == '+') s = s + next(); while (Character.isDigit(nextNonBlank())) s = s + next(); if (nextNonBlank() == '.') { s = s + next(); while (Character.isDigit(nextNonBlank())) s = s + next(); } if (nextNonBlank() == 'E' || nextNonBlank() == 'e') { s = s + 'E'; next(); if (nextNonBlank() == '+' || nextNonBlank() == '-') s = s + next(); while (Character.isDigit(nextNonBlank())) s = s + next(); } return Double.parseDouble(s); }
public int findEndOfOperand() { int i; for (i = index; i < line.length(); i++) { char c = line.charAt(i); if (!Character.isDigit(c)) return i; } return i; }
public static void debugger() { //Debug.println('m', "Debugger not implemented"); int num; char inputChar; // char read from input stream Interrupt.dumpState(); dumpState(); System.out.print(Nachos.stats.totalTicks + "> "); System.out.flush(); // get user input, character at a time. try { inputChar = (char)(System.in.read()); } catch (IOException _) { inputChar = 'x'; } if (inputChar == 'c') singleStep = false; else if (inputChar == '?') { System.out.println("Machine commands:"); System.out.println(" <return> execute one instruction"); System.out.println(" <number> run until the given timer tick"); System.out.println(" c run until completion"); System.out.println(" ? print this help message"); } else if (Character.isDigit(inputChar)) { int tempNum = 0; while (Character.isDigit(inputChar)) { tempNum *= 10; tempNum += Character.digit(inputChar, 10); try { inputChar = (char)(System.in.read()); } catch (IOException _) { inputChar = 'x'; break; } runUntilTime = tempNum; } } }
public static void readDigitStar(ShortTermMemoryReader reader, StringBuilder sb) throws IOException { char c = (char) reader.read(); while (Character.isDigit(c)) { sb.append(c); c = (char) reader.read(); } back(c, reader); }
/** * Gets the next token from a tokenizer and converts it to a double. * * @return The next token in the stream, as a double. * @throws TextParseException The input was invalid or not a double. * @throws IOException An I/O error occurred. */ public double getDouble() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) throw exception("expecting an integer"); try { return Double.parseDouble(next); } catch (NumberFormatException e) { throw exception("expecting an floating point value"); } }
/** * Gets the next token from a tokenizer and converts it to a long. * * @return The next token in the stream, as a long. * @throws TextParseException The input was invalid or not a long. * @throws IOException An I/O error occurred. */ public long getLong() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) throw exception("expecting an integer"); try { return Long.parseLong(next); } catch (NumberFormatException e) { throw exception("expecting an integer"); } }
// check the lexim type Type getType(String _lexim) { if (_lexim == null || _lexim.length() == 0) { // checking the _lexim to see if we reached the end of file or and empty one System.out.println("EoF"); return null; // System.exit(0); } if (Character.isAlphabetic( _lexim.charAt( 0))) // if the first char is alphabetic then chech to see if the token is a keyword if // not return type is ID { for (String keyword1 : keyword) { if (_lexim.equals(keyword1)) { return Type.keyword; } } return Type.id; } else if (Character.isDigit(_lexim.charAt(0)) || _lexim.charAt(0) == '-') { // check if it is a number for (int i = 1; i < _lexim.length(); i++) { if (!Character.isDigit(_lexim.charAt(i))) return Type.unkown; } return Type.number; } else if (!Character.isAlphabetic(_lexim.charAt(0)) && !Character.isDigit(_lexim.charAt(0))) { // checking the other casese like the =,+ ... for (String tempkeyword : keyword) { if (_lexim.equals(tempkeyword)) { return Type.keyword; } } if (_lexim.charAt(0) == '\'' && _lexim.charAt(2) == '\'') { // checking the value of a char var type return Type.value; } } return Type.unkown; }
private int getDataLength(String s) { int i; for (i = 0; i < s.length() && !Character.isDigit(s.charAt(i)); i++) ; // do it if (i == s.length()) return -1; String len_str = s.substring(i); try { return Integer.parseInt(len_str); } catch (NumberFormatException ex) { return -1; } }
// get signs using an additional arg for a target rel private Collection<Sign> getSignsFromPredAndTargetRel(String pred, String targetRel) { Collection<Word> words = (Collection<Word>) _predToWords.get(pred); String specialTokenConst = null; // for robustness, when using supertagger, add words for pred sans sense index int dotIndex = -1; if (_supertagger != null && !Character.isDigit(pred.charAt(0)) && // skip numbers (dotIndex = pred.lastIndexOf('.')) > 0 && pred.length() > dotIndex + 1 && pred.charAt(dotIndex + 1) != '_') // skip titles, eg Mr._Smith { String barePred = pred.substring(0, dotIndex); Collection<Word> barePredWords = (Collection<Word>) _predToWords.get(barePred); if (words == null) words = barePredWords; else if (barePredWords != null) { Set<Word> unionWords = new HashSet<Word>(words); unionWords.addAll(barePredWords); words = unionWords; } } if (words == null) { specialTokenConst = tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(pred)); if (specialTokenConst == null) return null; // lookup words with pred = special token const Collection<Word> specialTokenWords = (Collection<Word>) _predToWords.get(specialTokenConst); // replace special token const with pred if (specialTokenWords == null) return null; words = new ArrayList<Word>(specialTokenWords.size()); for (Iterator<Word> it = specialTokenWords.iterator(); it.hasNext(); ) { Word stw = it.next(); Word w = Word.createSurfaceWord(stw, pred); words.add(w); } } List<Sign> retval = new ArrayList<Sign>(); for (Iterator<Word> it = words.iterator(); it.hasNext(); ) { Word w = it.next(); try { SignHash signs = getSignsFromWord(w, specialTokenConst, pred, targetRel); retval.addAll(signs.asSignSet()); } // shouldn't happen catch (LexException exc) { System.err.println("Unexpected lex exception for word " + w + ": " + exc); } } return retval; }
private boolean isFirstCharStripable(String str) { if (Character.isDigit(str.charAt(0))) return true; if (str.startsWith(" ")) return true; if (str.startsWith("-")) return true; if (str.startsWith("_")) return true; if (str.startsWith(".")) return true; return false; }
public Integer read(ShortTermMemoryReader reader) throws RowColumnReaderException { try { removeSpaces(reader); char c = (char) reader.read(); if (Character.isDigit(c) || c == '-' || c == '+') { StringBuilder sb = new StringBuilder(); sb.append(c); readDigitStar(reader, sb); return Integer.parseInt(sb.toString()); } throw new Exception("Unexpected symbol " + c); } catch (Exception e) { throw reader.getException("Integer Parser Error " + e.getMessage()); } }
String version(Version version, String mask) { if (version == null) { String v = domain.getProperty("@"); if (v == null) { domain.error( "No version specified for ${version} or ${range} and no implicit version ${@} either, mask=%s", mask); v = "0"; } version = new Version(v); } StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); String result = null; if (c != '~') { if (i == 3) { result = version.getQualifier(); } else if (Character.isDigit(c)) { // Handle masks like +00, =+0 result = String.valueOf(c); } else { int x = version.get(i); switch (c) { case '+': x++; break; case '-': x--; break; case '=': break; } result = Integer.toString(x); } if (result != null) { sb.append(del); del = "."; sb.append(result); } } } return sb.toString(); }
/** * Builds the phonetic code of the word. * * @param word the word to transform * @return the phonetic transformation of the word */ public String transform(String word) { if (ruleArray == null) return null; TransformationRule rule; StringBuffer str = new StringBuffer(word.toUpperCase()); int strLength = str.length(); int startPos = 0, add = 1; while (startPos < strLength) { add = 1; if (Character.isDigit(str.charAt(startPos))) { StringUtility.replace(str, startPos, startPos + DIGITCODE.length(), DIGITCODE); startPos += add; continue; } for (int i = 0; i < ruleArray.length; i++) { // System.out.println("Testing rule#:"+i); rule = (TransformationRule) ruleArray[i]; if (rule.startsWithExp() && startPos > 0) continue; if (startPos + rule.lengthOfMatch() > strLength) { continue; } if (rule.isMatching(str, startPos)) { String replaceExp = rule.getReplaceExp(); add = replaceExp.length(); StringUtility.replace(str, startPos, startPos + rule.getTakeOut(), replaceExp); strLength -= rule.getTakeOut(); strLength += add; // System.out.println("Replacing with rule#:"+i+" add="+add); break; } } startPos += add; } // System.out.println(word); // System.out.println(str.toString()); return str.toString(); }
boolean readNumber() { int _c; int _start_idx = this.idx; do { _c = getNext(); // abort on incomplete string if (_c == Integer.MIN_VALUE) { return false; } } while (Character.isDigit((char) _c)); this.idx--; String _digit_str = new String(this.buffer, _start_idx, this.idx - _start_idx); try { this.lastDigit = Integer.parseInt(_digit_str); } catch (NumberFormatException _nfe) { // should not happen - ignore } return true; }
private void checkForInputIn(String programString) { String added = ""; String numstr = ""; int index = 0; int numindex = 0; int spaceindex = 0; int parenindex = 0; int endindex = 0; while (true) { index = programString.indexOf("input.in"); if (index == -1) break; // System.out.println(programString + " " + index); numindex = index + 8; if (!Character.isDigit(programString.charAt(numindex))) { programString = programString.substring(numindex); continue; } spaceindex = programString.indexOf(' ', numindex); parenindex = programString.indexOf(')', numindex); if (spaceindex == -1) endindex = parenindex; else if (parenindex == -1) endindex = spaceindex; else endindex = Math.min(spaceindex, parenindex); numstr = programString.substring(numindex, endindex); // Check for doubles in added if (added.indexOf(" " + numstr + " ") == -1) { added = added + " " + numstr + " "; _interpreter.AddInstruction("input.in" + numstr, new InputInN(Integer.parseInt(numstr))); } programString = programString.substring(numindex); } }
@Override public void replace( DocumentFilter.FilterBypass fp, int offset, int length, String string, AttributeSet aset) throws BadLocationException { Document doc = fp.getDocument(); String oldText = doc.getText(0, doc.getLength()); StringBuilder sb = new StringBuilder(oldText); sb.replace(offset, offset + length, oldText); int len = string.length(); boolean isValidInteger = true; for (int i = 0; i < len; i++) { if (!Character.isDigit(string.charAt(i))) { isValidInteger = false; break; } } if (isValidInteger && verifyText(sb.toString())) { super.replace(fp, offset, length, string, aset); } else Toolkit.getDefaultToolkit().beep(); }
public void eval() { boolean parenFound = true; // Pretend that we have found a '(' at the beginning while (more()) { if (nextNonBlank() == '(') { parenFound = true; getOperator().handle(ostack, nstack); } else if (Character.isDigit(nextNonBlank()) || Character.isLetter(nextNonBlank()) || parenFound) { parenFound = false; nstack.push(getOperand()); } else getOperator().handle(ostack, nstack); } while (!ostack.isEmpty()) { ostack.pop().eval(ostack, nstack); } System.out.println("Answer: " + nstack.pop().eval()); }
/** * Method to invoke when we encounter a block of text in the CSV file that is the contents of a * variable. * * @param csvFile The csvFile we are currently parsing. * @param var The variable that we will be adding cells too. * @param The populator to use when converting the contents of the cell into a datavalue that can * be inserted into the spreadsheet. * @return The next line in the file that is not part of the block of text in the CSV file. * @throws IOException If unable to read the file correctly. */ private String parseEntries( final BufferedReader csvFile, final Variable var, final EntryPopulator populator) throws IOException { // Keep parsing lines and putting them in the newly formed nominal // variable until we get to a line indicating the end of file or a new // variable section. String line = csvFile.readLine(); while ((line != null) && Character.isDigit(line.charAt(0))) { // Split the line into tokens using a comma delimiter. String[] tokens = line.split(","); // BugzID: 1075 - If the line ends with an escaped new line - add // the next line to the current text field. while ((line != null) && line.endsWith("\\") && !line.endsWith("\\\\")) { line = csvFile.readLine(); String content = tokens[tokens.length - 1]; content = content.substring(0, content.length() - 1); tokens[tokens.length - 1] = content + '\n' + line; } Cell newCell = var.createCell(); // Set the onset and offset from tokens in the line. newCell.setOnset(tokens[DATA_ONSET]); newCell.setOffset(tokens[DATA_OFFSET]); populator.populate(tokens, newCell.getValue()); // Get the next line in the file for reading. line = csvFile.readLine(); } return line; }
/** * Get any children that match this name or path. Similar to getChild(), but will grab multiple * matches rather than only the first. * * @param name element name or path/to/element * @return array of child elements that match * @author processing.org */ public XML[] getChildren(String name) { if (name.length() > 0 && name.charAt(0) == '/') { throw new IllegalArgumentException("getChildren() should not begin with a slash"); } if (name.indexOf('/') != -1) { return getChildrenRecursive(PApplet.split(name, '/'), 0); } // if it's a number, do an index instead // (returns a single element array, since this will be a single match if (Character.isDigit(name.charAt(0))) { return new XML[] {getChild(Integer.parseInt(name))}; } int childCount = getChildCount(); XML[] matches = new XML[childCount]; int matchCount = 0; for (int i = 0; i < childCount; i++) { XML kid = getChild(i); String kidName = kid.getName(); if (kidName != null && kidName.equals(name)) { matches[matchCount++] = kid; } } return (XML[]) PApplet.subset(matches, 0, matchCount); }
/** * Internal helper function for getChild(String). * * @param items result of splitting the query on slashes * @param offset where in the items[] array we're currently looking * @return matching element or null if no match * @author processing.org */ protected XML getChildRecursive(String[] items, int offset) { // if it's a number, do an index instead if (Character.isDigit(items[offset].charAt(0))) { XML kid = getChild(Integer.parseInt(items[offset])); if (offset == items.length - 1) { return kid; } else { return kid.getChildRecursive(items, offset + 1); } } int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { XML kid = getChild(i); String kidName = kid.getName(); if (kidName != null && kidName.equals(items[offset])) { if (offset == items.length - 1) { return kid; } else { return kid.getChildRecursive(items, offset + 1); } } } return null; }