void solve(InputReader in) { try { long start = System.currentTimeMillis(); F[0] = BigInteger.ONE; for (i = 1; i <= 30; ++i) F[i] = F[i - 1].multiply(BigInteger.valueOf(i)); for (i = 1; i <= 30; ++i) { for (j = 1; j <= i; ++j) { C[i][j] = getResult(i, j); } } t = in.nextInt(); while (t-- > 0) { for (i = 1; i <= 30; ++i) g[i] = new ArrayList(); n = in.nextInt(); for (i = 1; i <= n; ++i) a[i] = in.nextInt(); root = a[1]; p = 2; Construct(root, 1, 30); Pair ans = Calculate(root); System.out.println(ans.x); } long end = System.currentTimeMillis(); if (time) System.out.println("Execution time: " + (double) (end - start) / 1000.0); } catch (Exception e) { System.out.println("Error: " + e); } ; }
// BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.8 (beta) modified by pivanof private static boolean KawigiEdit_RunTest( int testNum, int p0, int p1, boolean hasAnswer, String p2) { System.out.print("Test " + testNum + ": [" + p0 + "," + p1); System.out.println("]"); KLastNonZeroDigits obj; String answer; obj = new KLastNonZeroDigits(); long startTime = System.currentTimeMillis(); answer = obj.getKDigits(p0, p1); long endTime = System.currentTimeMillis(); boolean res; res = true; System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds"); if (hasAnswer) { System.out.println("Desired answer:"); System.out.println("\t" + "\"" + p2 + "\""); } System.out.println("Your answer:"); System.out.println("\t" + "\"" + answer + "\""); if (hasAnswer) { res = answer.equals(p2); } if (!res) { System.out.println("DOESN'T MATCH!!!!"); } else if ((endTime - startTime) / 1000.0 >= 2) { System.out.println("FAIL the timeout"); res = false; } else if (hasAnswer) { System.out.println("Match :-)"); } else { System.out.println("OK, but is it right?"); } System.out.println(""); return res; }
// BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit-pf 2.3.0 private static boolean KawigiEdit_RunTest(int testNum, int p0, boolean hasAnswer, int p1) { System.out.print("Test " + testNum + ": [" + p0); System.out.println("]"); EmoticonsDiv1 obj; int answer; obj = new EmoticonsDiv1(); long startTime = System.currentTimeMillis(); answer = obj.printSmiles(p0); long endTime = System.currentTimeMillis(); boolean res; res = true; System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds"); if (hasAnswer) { System.out.println("Desired answer:"); System.out.println("\t" + p1); } System.out.println("Your answer:"); System.out.println("\t" + answer); if (hasAnswer) { res = answer == p1; } if (!res) { System.out.println("DOESN'T MATCH!!!!"); } else if ((endTime - startTime) / 1000.0 >= 2) { System.out.println("FAIL the timeout"); res = false; } else if (hasAnswer) { System.out.println("Match :-)"); } else { System.out.println("OK, but is it right?"); } System.out.println(""); return res; }
// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (Exception e) { // This catches any other errors we might get. println("Some error thrown", progErr); logError(e.toString()); displayLog(); return; } }
/** * Method to provide a gross level of synchronization with the target monitored jvm. * * <p>gross synchronization works by polling for the hotspot.rt.hrt.ticks counter, which is the * last counter created by the StatSampler initialization code. The counter is updated when the * watcher thread starts scheduling tasks, which is the last thing done in vm initialization. */ protected void synchWithTarget(Map<String, Monitor> map) throws MonitorException { /* * synch must happen with syncWaitMs from now. Default is 5 seconds, * which is reasonabally generous and should provide for extreme * situations like startup delays due to allocation of large ISM heaps. */ long timeLimit = System.currentTimeMillis() + syncWaitMs; String name = "hotspot.rt.hrt.ticks"; LongMonitor ticks = (LongMonitor) pollFor(map, name, timeLimit); /* * loop waiting for the ticks counter to be non zero. This is * an indication that the jvm is initialized. */ log("synchWithTarget: " + lvmid + " "); while (ticks.longValue() == 0) { log("."); try { Thread.sleep(20); } catch (InterruptedException e) { } if (System.currentTimeMillis() > timeLimit) { lognl("failed: " + lvmid); throw new MonitorException("Could Not Synchronize with target"); } } lognl("success: " + lvmid); }
// BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof private static boolean KawigiEdit_RunTest( int testNum, int[] p0, int[] p1, int[] p2, boolean hasAnswer, int p3) { System.out.print("Test " + testNum + ": [" + "{"); for (int i = 0; p0.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p0[i]); } System.out.print("}" + "," + "{"); for (int i = 0; p1.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p1[i]); } System.out.print("}" + "," + "{"); for (int i = 0; p2.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p2[i]); } System.out.print("}"); System.out.println("]"); KeyDungeonDiv2 obj; int answer; obj = new KeyDungeonDiv2(); long startTime = System.currentTimeMillis(); answer = obj.countDoors(p0, p1, p2); long endTime = System.currentTimeMillis(); boolean res; res = true; System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds"); if (hasAnswer) { System.out.println("Desired answer:"); System.out.println("\t" + p3); } System.out.println("Your answer:"); System.out.println("\t" + answer); if (hasAnswer) { res = answer == p3; } if (!res) { System.out.println("DOESN'T MATCH!!!!"); } else if ((endTime - startTime) / 1000.0 >= 2) { System.out.println("FAIL the timeout"); res = false; } else if (hasAnswer) { System.out.println("Match :-)"); } else { System.out.println("OK, but is it right?"); } System.out.println(""); return res; }
/** The main program for ReTrace. */ public static void main(String[] args) { if (args.length < 1) { System.err.println( "Usage: java proguard.ReTrace [-verbose] <mapping_file> [<stacktrace_file>]"); System.exit(-1); } String regularExpresssion = STACK_TRACE_EXPRESSION; boolean verbose = false; int argumentIndex = 0; while (argumentIndex < args.length) { String arg = args[argumentIndex]; if (arg.equals(REGEX_OPTION)) { regularExpresssion = args[++argumentIndex]; } else if (arg.equals(VERBOSE_OPTION)) { verbose = true; } else { break; } argumentIndex++; } if (argumentIndex >= args.length) { System.err.println( "Usage: java proguard.ReTrace [-regex <regex>] [-verbose] <mapping_file> [<stacktrace_file>]"); System.exit(-1); } File mappingFile = new File(args[argumentIndex++]); File stackTraceFile = argumentIndex < args.length ? new File(args[argumentIndex]) : null; ReTrace reTrace = new ReTrace(regularExpresssion, verbose, mappingFile, stackTraceFile); try { // Execute ReTrace with its given settings. reTrace.execute(); } catch (IOException ex) { if (verbose) { // Print a verbose stack trace. ex.printStackTrace(); } else { // Print just the stack trace message. System.err.println("Error: " + ex.getMessage()); } System.exit(1); } System.exit(0); }
public static void main(String[] args) { long start = System.currentTimeMillis(); Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases); int previousKey = -1; int previousValue = 0; int cycleNumber = 0; Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>(); for (int i = 0; i < numberOfTestCases; i++) { int numberOfCycles = input.nextInt(); testCases.put(numberOfCycles, 1); order.add(numberOfCycles); } for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) { int numberOfCycles; int initialHeight; if (previousKey == -1) { numberOfCycles = entry.getKey(); initialHeight = entry.getValue(); } else { numberOfCycles = entry.getKey() - previousKey; initialHeight = previousValue; } for (int i = 0; i < numberOfCycles; i++) { if (cycleNumber % 2 == 0) { initialHeight *= 2; } else { initialHeight += 1; } cycleNumber++; } entry.setValue(initialHeight); previousKey = entry.getKey(); previousValue = initialHeight; } for (Integer element : order) { System.out.println(testCases.get(element)); } long elapsed = System.currentTimeMillis() - start; System.out.println("time: " + elapsed); }
private void chkFPS() { if (fpsCount == 0) { fpsTime = System.currentTimeMillis() / 1000; fpsCount++; return; } fpsCount++; long time = System.currentTimeMillis() / 1000; if (time != fpsTime) { lastFPS = fpsCount; fpsCount = 1; fpsTime = time; } }
// To be called exactly twice by the child process public static void rendezvousChild() { try { for (int i = 0; i < 100; i++) { System.gc(); System.runFinalization(); Thread.sleep(50); } System.out.write((byte) '\n'); System.out.flush(); System.in.read(); } catch (Throwable t) { throw new Error(t); } }
public void run() { Map read; boolean shouldRead = go_read; String command = null; long last = 0; try { /* swallow the banner if requested to do so */ if (swallow) { readResponse(); } while (shouldRead) { synchronized (listeners) { if (commands.size() > 0) { command = (String) commands.removeFirst(); } } if (command != null) { _sendString(command); command = null; lastRead = System.currentTimeMillis(); } long now = System.currentTimeMillis(); if (this.window != null && !this.window.isShowing() && (now - last) < 1500) { /* check if our window is not showing... if not, then we're going to switch to a very reduced read schedule. */ } else { read = readResponse(); if (read == null || "failure".equals(read.get("result") + "")) { break; } processRead(read); last = System.currentTimeMillis(); } Thread.sleep(100); synchronized (listeners) { shouldRead = go_read; } } } catch (Exception javaSucksBecauseItMakesMeCatchEverythingFuckingThing) { javaSucksBecauseItMakesMeCatchEverythingFuckingThing.printStackTrace(); } }
/** * Statically analyze a query for various properties. * * @param query the query to analyze * @param params parameters for the query; if necessary parameters are left out they will be * listed as required variables in the analysis * @return a query analysis facet */ public QueryAnalysis analyze(String query, Object... params) { if (presub) query = presub(query, params); long t1 = System.currentTimeMillis(), t2 = 0, t3 = 0; DBBroker broker = null; try { broker = db.acquireBroker(); prepareContext(broker); final org.exist.source.Source source = buildQuerySource(query, params, "analyze"); final XQuery xquery = broker.getXQueryService(); final XQueryPool pool = xquery.getXQueryPool(); CompiledXQuery compiledQuery = pool.borrowCompiledXQuery(broker, source); try { AnalysisXQueryContext context; if (compiledQuery == null) { context = new AnalysisXQueryContext(broker, AccessContext.INTERNAL_PREFIX_LOOKUP); buildXQueryStaticContext(context, false); buildXQueryDynamicContext(context, params, null, false); t2 = System.currentTimeMillis(); compiledQuery = xquery.compile(context, source); t3 = System.currentTimeMillis(); } else { context = (AnalysisXQueryContext) compiledQuery.getContext(); t2 = System.currentTimeMillis(); } return new QueryAnalysis( compiledQuery, Collections.unmodifiableSet(context.requiredVariables), Collections.unmodifiableSet(context.requiredFunctions)); } finally { if (compiledQuery != null) pool.returnCompiledXQuery(source, compiledQuery); } } catch (XPathException e) { LOG.warn( "query compilation failed -- " + query + " -- " + (params == null ? "" : " with params " + Arrays.asList(params)) + (bindings.isEmpty() ? "" : " and bindings " + bindings)); throw new DatabaseException("failed to compile query", e); } catch (IOException e) { throw new DatabaseException("unexpected exception", e); } catch (PermissionDeniedException e) { throw new DatabaseException("permission denied", e); } finally { db.releaseBroker(broker); STATS.update(query, t1, t2, t3, 0, System.currentTimeMillis()); } }
// BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit-pf 2.3.0 private static boolean KawigiEdit_RunTest( int testNum, int[] p0, int[] p1, boolean hasAnswer, double p2) { System.out.print("Test " + testNum + ": [" + "{"); for (int i = 0; p0.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p0[i]); } System.out.print("}" + "," + "{"); for (int i = 0; p1.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p1[i]); } System.out.print("}"); System.out.println("]"); GreaterGame obj; double answer; obj = new GreaterGame(); long startTime = System.currentTimeMillis(); answer = obj.calc(p0, p1); long endTime = System.currentTimeMillis(); boolean res; res = true; System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds"); if (hasAnswer) { System.out.println("Desired answer:"); System.out.println("\t" + p2); } System.out.println("Your answer:"); System.out.println("\t" + answer); if (hasAnswer) { res = answer == answer && Math.abs(p2 - answer) <= 1e-9 * Math.max(1.0, Math.abs(p2)); } if (!res) { System.out.println("DOESN'T MATCH!!!!"); } else if ((endTime - startTime) / 1000.0 >= 2) { System.out.println("FAIL the timeout"); res = false; } else if (hasAnswer) { System.out.println("Match :-)"); } else { System.out.println("OK, but is it right?"); } System.out.println(""); return res; }
void getTable() { if (chooser == null) { File userdir = new File(System.getProperty("user.dir")); chooser = new JFileChooser(userdir); } if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); fileLength = file.length(); setTitle(windowTitle + ": " + file.getAbsolutePath()); int size = Key.getEncryptionKeySize(this, true); key = Key.getEncryptionKey(this, true, size); if (key == null) key = defaultKey; initCipher(); } else System.exit(0); }
private byte[] loadClassData(String className) throws IOException { Playground.println("Loading class " + className + ".class", warning); File f = new File(System.getProperty("user.dir") + "/" + className + ".class"); byte[] b = new byte[(int) f.length()]; new FileInputStream(f).read(b); return b; }
private InstanceList readFile() throws IOException { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fileName), encoding); ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+"))); pipeList.add(new TokenSequence2FeatureSequence()); InstanceList testing = new InstanceList(new SerialPipes(pipeList)); try { while (scanner.hasNextLine()) { String text = scanner.nextLine(); text = text.replaceAll("\\x0d", ""); Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$"); Matcher matcher = patten.matcher(text); if (matcher.find()) { docIds.add(matcher.group(1)); testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null)); } } } finally { scanner.close(); } return testing; }
public static void main(String[] args) { if (args.length == 0) { printDocs(); System.exit(0); } new ArupPipelineWrapper(args); }
/** * Method to poll the instrumentation memory for a counter with the given name. The polling period * is bounded by the timeLimit argument. */ protected Monitor pollFor(Map<String, Monitor> map, String name, long timeLimit) throws MonitorException { Monitor monitor = null; log("polling for: " + lvmid + "," + name + " "); pollForEntry = nextEntry; while ((monitor = map.get(name)) == null) { log("."); try { Thread.sleep(20); } catch (InterruptedException e) { } long t = System.currentTimeMillis(); if ((t > timeLimit) || (overflow.intValue() > 0)) { lognl("failed: " + lvmid + "," + name); dumpAll(map, lvmid); throw new MonitorException("Could not find expected counter"); } getNewMonitors(map); } lognl("success: " + lvmid + "," + name); return monitor; }
private static String expand(String str) { if (str == null) { return null; } StringBuilder result = new StringBuilder(); Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)"); while (true) { Matcher matcher = re.matcher(str); if (matcher.matches()) { result.append(matcher.group(1)); String property = matcher.group(2); if (property.equals("/")) { property = "file.separator"; } String value = System.getProperty(property); if (value != null) { result.append(value); } str = matcher.group(3); } else { result.append(str); break; } } return result.toString(); }
void add(Target t) { SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); boolean connected = sc.connect(t.address); t.channel = sc; t.connectStart = System.currentTimeMillis(); if (connected) { t.connectFinish = t.connectStart; sc.close(); printer.add(t); } else { synchronized (pending) { pending.add(t); } sel.wakeup(); } } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) { } } t.failure = x; printer.add(t); } }
public static void main(String[] args) { if (args.length == 0) { printDocs(); System.exit(0); } new IndexFastas(args); }
/** * The ActionListener implementation * * @param event the event. */ public void actionPerformed(ActionEvent event) { String searchText = textField.getText().trim(); if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) { textPane.setText("Blank search text is not allowed for large IdTables."); } else { File outputFile = null; if (saveAs.isSelected()) { outputFile = chooser.getSelectedFile(); if (outputFile != null) { String name = outputFile.getName(); int k = name.lastIndexOf("."); if (k != -1) name = name.substring(0, k); name += ".txt"; File parent = outputFile.getAbsoluteFile().getParentFile(); outputFile = new File(parent, name); chooser.setSelectedFile(outputFile); } if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0); outputFile = chooser.getSelectedFile(); } textPane.setText(""); Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile); searcher.start(); } }
/** * 发起同步请求,获取后台信息,直接显示在页面上 * * @param req * @param res */ public static void sync(HttpServletRequest req, HttpServletResponse res) { System.setProperty("0", "aaaaaaaa"); // h.put(i+"","aaaaaaaaaaaaaaaaaaaaaaaa"); // i++; // System.out.println("*************************system prop is " + // System.getProperties()); IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt(); SSysOperatorsListHolder holder = new SSysOperatorsListHolder(); CBSErrorMsg errMsg = new CBSErrorMsg(); try { res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>"); int result = iAsyncMgntInt.select_sysOperators(holder, errMsg); System.out.println("*****result is " + result); if (result != 0) { res.getWriter().println(errMsg.get_errorMsg() + ":" + errMsg.get_errorCode()); } SSysOperatorsList list = holder.value; int size = list.size(); res.getWriter().println("<pre>"); for (int i = 0; i < size; i++) { SSysOperators opers = (SSysOperators) list.get(i); res.getWriter().println(i + ":" + opers.get_loginName()); } res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>"); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { if (args.length < 1) { print(usage); System.exit(0); } int lines = 0; try { Class<?> c = Class.forName(args[0]); Method[] methods = c.getMethods(); Constructor[] ctors = c.getConstructors(); if (args.length == 1) { for (Method method : methods) print(p.matcher(method.toString()).replaceAll("")); for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll("")); lines = methods.length + ctors.length; } else { for (Method method : methods) if (method.toString().indexOf(args[1]) != -1) { print(p.matcher(method.toString()).replaceAll("")); lines++; } for (Constructor ctor : ctors) if (ctor.toString().indexOf(args[1]) != -1) { print(p.matcher(ctor.toString()).replaceAll("")); lines++; } } } catch (ClassNotFoundException e) { print("No such class: " + e); } }
// constructor public ArupPipelineWrapper(String[] args) { long startTime = System.currentTimeMillis(); processArgs(args); buildXmlPropertiesFile(); buildXmlTemplate(); executePipelineJob(); deleteTempFiles(); // finish and calc run time double diffTime = ((double) (System.currentTimeMillis() - startTime)) / 60000; System.out.println("\nDone! " + Math.round(diffTime) + " minutes\n"); }
void run() throws Exception { in = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); // pr(System.currentTimeMillis() - s + "ms"); }
public static void main(String[] args) throws Throwable { final ReentrantLock lock = new ReentrantLock(); lock.lock(); final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); final ReentrantReadWriteLock.ReadLock readLock = rwlock.readLock(); final ReentrantReadWriteLock.WriteLock writeLock = rwlock.writeLock(); rwlock.writeLock().lock(); final BlockingQueue<Object> q = new LinkedBlockingQueue<Object>(); final Semaphore fairSem = new Semaphore(0, true); final Semaphore unfairSem = new Semaphore(0, false); // final int threads = // rnd.nextInt(Runtime.getRuntime().availableProcessors() + 1) + 1; final int threads = 3; // On Linux, this test runs very slowly for some reason, // so use a smaller number of iterations. // Solaris can handle 1 << 18. // On the other hand, jmap is much slower on Solaris... final int iterations = 1 << 8; final CyclicBarrier cb = new CyclicBarrier(threads + 1); for (int i = 0; i < threads; i++) new Thread() { public void run() { try { final Random rnd = new Random(); for (int j = 0; j < iterations; j++) { if (j == iterations / 10 || j == iterations - 1) { cb.await(); // Quiesce cb.await(); // Resume } // int t = rnd.nextInt(2000); int t = rnd.nextInt(900); check(!lock.tryLock(t, NANOSECONDS)); check(!readLock.tryLock(t, NANOSECONDS)); check(!writeLock.tryLock(t, NANOSECONDS)); equal(null, q.poll(t, NANOSECONDS)); check(!fairSem.tryAcquire(t, NANOSECONDS)); check(!unfairSem.tryAcquire(t, NANOSECONDS)); } } catch (Throwable t) { unexpected(t); } } }.start(); cb.await(); // Quiesce rendezvousChild(); // Measure cb.await(); // Resume cb.await(); // Quiesce rendezvousChild(); // Measure cb.await(); // Resume System.exit(failed); }
public abstract static class Message { public final long time = System.currentTimeMillis(); public abstract Text text(); public abstract Tex tex(); public abstract Coord sz(); }
public String _env(String args[]) { verifyCommand(args, "${env;<name>}, get the environmet variable", null, 2, 2); try { return System.getenv(args[1]); } catch (Throwable t) { return null; } }
public static void main(String args[]) { // System.out.println( "Starting Jinan..." ); LineNumberReader in = null; BufferedWriter out = null; try { in = new LineNumberReader(new FileReader("Jinan.txt")); out = new BufferedWriter(new FileWriter("format.txt")); } catch (IOException e) { System.out.println(e); System.exit(-1); } String line; // 下面的表达式为:以K或没有K开头,接着是若干数字,然后是“路”字。 // 注意()表示group,以便提取其中的信息 Pattern p = Pattern.compile("^([Kk]?\\d+路).*$"); Matcher m; boolean flag = true; try { while (true) { line = in.readLine(); if (line == null) break; else if (line.equals("")) continue; m = p.matcher(line); if (flag != m.find()) // 这里必须先用find()触发匹配过程,才能开始使用 throw new RuntimeException("File format error: " + in.getLineNumber()); if (flag == true) { out.write(m.group(1)); // group(0) is the entire string, group(1) is the right one out.write(" "); flag = false; } else { out.write(line); out.newLine(); flag = true; } } in.close(); out.close(); } catch (IOException e) { System.out.println(e); System.exit(-1); } }