/** @return The next command from the user. */ public Command getCommands() { String inputLine; // will hold the full input line String word1 = null; String word2 = null; System.out.print("> "); // print prompt inputLine = reader.nextLine(); // Find up to two words on the line. Scanner tokenizer = new Scanner(inputLine); if (tokenizer.hasNext()) { word1 = tokenizer.next(); // get first word if (tokenizer.hasNext()) { word2 = tokenizer.next(); // get second word // note: we just ignore the rest of the input line. } } // Now check whether this word is known. If so, create a command // with it. If not, create a "null" command (for unknown command). if (commands.isCommand(word1)) { return new Command(word1, word2); } else { return new Command(null, word2); } }
public String loadStationData() { int x = 0; try { File f = new File("data\\FBIN.txt"); Scanner scan = new Scanner(f); while (breakLoop == false) { temp = scan.nextLine(); if (scan.hasNext() && x > 6) { x++; stations.add(temp); } else if (scan.hasNext() && x < 7) { x++; } else { breakLoop = true; } } scan.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } breakLoop = false; return temp; }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); Scanner scL; String s, a; char c; boolean t; while (true) { s = sc.nextLine(); if (s.equals("*")) { break; } scL = new Scanner(s); a = ""; c = '\0'; t = true; if (scL.hasNext()) { a = scL.next().toLowerCase(); c = a.charAt(0); } while (scL.hasNext() && t) { a = scL.next().toLowerCase(); if (a.charAt(0) != c) { t = false; } } if (t) { System.out.println("Y"); } else { System.out.println("N"); } } }
public static void main(String args[]) throws IOException { Scanner sf = new Scanner(new File("D:\\IB CS\\temp_Aman\\StudentsScores.in.txt")); int maxIndx = -1; String text[] = new String[1000]; while (sf.hasNext()) // this allows the program to assign each line in the text file a variable { maxIndx++; text[maxIndx] = sf.nextLine(); } for (int j = 0; j <= 4; j++) { Scanner sc = new Scanner(text[j]); String name = sc.next(); // this helps identify the Strings, which are the names of students, in each // line double sum = 0.0; // it starts the sum and count variables with zero because they change as they move // along with the while loop int count = 0; while (sc.hasNext()) { sum = sum + sc.nextDouble(); // this while loop helps find out the number of integers in the // line and adds all of these numbers as well count = count + 1; } double avg = sum / count; int y = (int) Math.round(avg); // this converts the double variable avg to an integer System.out.println(name + "," + " average = " + y); } }
private void leLabirinto(Scanner arquivo) throws Exception { String cmd = arquivo.next().toLowerCase(); while (cmd.equals("room")) { int salaId = arquivo.nextInt(); salas[salaId] = new Sala(); Sala sala = salas[salaId]; String direcao = arquivo.next(); do { if (arquivo.hasNextInt()) { salaId = arquivo.nextInt(); } else if (arquivo.next().equalsIgnoreCase("EXIT")) { salaId = 0; } else break; sala.addConexao(direcao, salaId); if (!arquivo.hasNext()) return; cmd = arquivo.next().toLowerCase(); if (cmd.equals("trap")) { sala.setArmadilha(direcao); if (!arquivo.hasNext()) return; cmd = arquivo.next(); } direcao = cmd; } while (!cmd.equals("room")); } throw new Exception("Arquivo de descricao do labirinto invalido."); }
static void loadJumps() throws IOException { InputStream in = getInput(JUMPS_FNAME); Scanner sc = makeScanner(in); while (sc.hasNext()) try { int a = sc.nextInt(); int b = sc.nextInt(); StarSystem sa = systems.get(a); StarSystem sb = systems.get(b); Jump j = new Jump(sa, sb); sa.jumps.add(j); sb.jumps.add(j); jumps.add(j); } catch (Exception e) { System.err.println("Parsing error loading jumps."); if (sc.hasNext()) System.err.println("Problematic token: " + sc.next()); else System.err.println("No tokens remaining."); System.err.println("e"); sc.close(); in.close(); throw new RuntimeException(e); } sc.close(); in.close(); }
/** * This API compares if two files content is identical. It ignores extra spaces and new lines * while comparing * * @param sourceFile * @param destFile * @return * @throws Exception */ public static boolean isFilesIdentical(File sourceFile, File destFile) throws Exception { try { Scanner sourceFileScanner = new Scanner(sourceFile); Scanner destFileScanner = new Scanner(destFile); while (sourceFileScanner.hasNext()) { /* * If source file is having next token * then destination file also should have next token, * else they are not identical. */ if (!destFileScanner.hasNext()) { return false; } if (!sourceFileScanner.next().equals(destFileScanner.next())) { return false; } } /* * Handling the case where source file is empty * and destination file is having text */ if (destFileScanner.hasNext()) { return false; } else { return true; } } catch (Exception e) { e.printStackTrace(); throw e; } }
/** Does not close <var>r</var>. */ public static SrgFile read(Reader r, boolean reverse) throws IOException { @SuppressWarnings("resource") Scanner in = new Scanner(r); SrgFile rv = new SrgFile(); while (in.hasNextLine()) { if (in.hasNext("CL:")) { in.next(); String obf = in.next(); String deobf = in.next(); if (reverse) rv.classes.put(deobf, obf); else rv.classes.put(obf, deobf); } else if (in.hasNext("FD:")) { in.next(); String obf = in.next(); String deobf = in.next(); if (reverse) rv.fields.put(deobf, getLastComponent(obf)); else rv.fields.put(obf, getLastComponent(deobf)); } else if (in.hasNext("MD:")) { in.next(); String obf = in.next(); String obfdesc = in.next(); String deobf = in.next(); String deobfdesc = in.next(); if (reverse) rv.methods.put(deobf + deobfdesc, getLastComponent(obf)); else rv.methods.put(obf + obfdesc, getLastComponent(deobf)); } else { in.nextLine(); } } return rv; }
public void loadEnvironment(File modelFile) { reset(); try { Scanner input = new Scanner(modelFile); while (input.hasNext()) { Scanner line = new Scanner(input.nextLine()); if (line.hasNext()) { String type = line.next(); if (GRAVITY_KEYWORD.equals(type)) { gravityCommand(line); } else if (VISCOSITY_KEYWORD.equals(type)) { viscosityCommand(line); } else if (CENTEROFMASS_KEYWORD.equals(type)) { centerOfMassCommand(line); } else if (WALLREPULSION_KEYWORD.equals(type)) { wallRepulsionCommand(line); } } } input.close(); } catch (FileNotFoundException e) { // should not happen because File came from user selection e.printStackTrace(); } }
public boolean ok(String out, String reference) { // log.fine("out1: " + a); // log.fine("out2: " + b); Scanner sa = new Scanner(out); Scanner sb = new Scanner(reference); while (sa.hasNext() && sb.hasNext()) { if (sa.hasNextDouble() || sb.hasNextDouble()) { if (!sa.hasNextDouble() || !sb.hasNextDouble()) return true; double da = sa.nextDouble(); double db = sb.nextDouble(); double d_abs = Math.abs(da - db); double d_rel = d_abs / Math.abs(db); if (!(d_abs < EPS || d_rel < EPS)) { log.fine("NOK, " + da + " too far from " + db); return false; } } else { String xa = sa.next(); String xb = sb.next(); if (!xa.equals(xb)) { log.fine("NOK, " + xa + " != " + xb); return false; } } } if (sa.hasNext() || sb.hasNext()) { log.fine("NOK: different number of tokens."); return false; } return true; }
public String[] getEmail() { LinkedSet<String> ls = new LinkedSet<String>(); int counter = 0; String bod = this.getBody(); String from = this.getFrom(); Scanner f = new Scanner(from); Scanner b = new Scanner(bod); String pattern = "^[A-Za-z0-9]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; while (b.hasNext()) { String newString = b.next(); String finalString = newString.replaceAll(pattern, ""); if (newString.matches(pattern)) { ls.add(newString); counter++; } } while (f.hasNext()) { String newString = f.next(); String finalString = newString.replaceAll(pattern, ""); if (newString.matches(pattern)) { ls.add(newString); counter++; } } String[] Lastemails = new String[ls.size()]; if (ls.size() > 0) { for (int i = 0; i < ls.size(); i++) { Lastemails[i] = ls.get(i + 1); } } return Lastemails; }
public static void tokenize(String regexStr, String source, String delimiters) { // (1) System.out.print("Index: "); for (int i = 0; i < source.length(); i++) { System.out.print(i % 10); } System.out.println(); System.out.println("Target: " + source); System.out.println("Delimit: " + delimiters); System.out.println("Pattern: " + regexStr); System.out.print("Match: "); Pattern pattern = Pattern.compile(regexStr); // (2) Scanner lexer = new Scanner(source); // (3) if (!delimiters.equalsIgnoreCase("default")) lexer.useDelimiter(delimiters); // (5) while (lexer.hasNext()) { // (4) if (lexer.hasNext(pattern)) { // (5) String matchedStr = lexer.next(pattern); // (5) MatchResult matchResult = lexer.match(); // (6) int startCharIndex = matchResult.start(); int lastPlus1Index = matchResult.end(); int lastCharIndex = startCharIndex == lastPlus1Index ? lastPlus1Index : lastPlus1Index - 1; out.print("(" + startCharIndex + "," + lastCharIndex + ":" + matchedStr + ")"); } else { lexer.next(); // (7) } } System.out.println(); }
public void initialize() { try { InputStream stream = schema.getInputStream(); Scanner scanner = new Scanner(stream); StringBuilder sql = new StringBuilder(); while (scanner.hasNext()) { sql.append(scanner.nextLine()); sql.append("\n"); } scanner.close(); stream.close(); Connection connection = null; Statement statement = null; try { connection = dataSource.getConnection(); statement = connection.createStatement(); statement.execute(sql.toString()); } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { if (null != connection) { try { connection.close(); } catch (SQLException ex) { } } } stream = data.getInputStream(); scanner = new Scanner(stream); sql = new StringBuilder(); while (scanner.hasNext()) { sql.append(scanner.nextLine()); sql.append("\n"); } scanner.close(); stream.close(); connection = null; statement = null; try { connection = dataSource.getConnection(); statement = connection.createStatement(); statement.executeUpdate(sql.toString()); } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { if (null != connection) { try { connection.close(); } catch (SQLException ex) { } } } } catch (IOException e) { e.printStackTrace(); } }
public static void testMatchSampleFiles(String Path1, String Path2) { try { Scanner sc1 = new Scanner(new File(Path1)); Scanner sc2 = new Scanner(new File(Path2)); Assert.assertTrue(sc1.hasNext()); Assert.assertTrue(sc2.hasNext()); String header1 = sc1.next(); String header2 = sc2.next(); Assert.assertTrue(header1.equals(header2)); while (sc1.hasNext() && sc2.hasNext()) { String line1 = sc1.next(); String line2 = sc2.next(); Assert.assertTrue(line1.equals(line2)); } sc1.close(); sc2.close(); } catch (FileNotFoundException e) { Assert.assertTrue(false); e.printStackTrace(); } }
public final void loadAllPresets() { try { final File _f = new File("plugins/VoxelSniper/presetsBySniper/" + this.player.getName() + ".txt"); if (_f.exists()) { final Scanner _snr = new Scanner(_f); final int[] _presetsHolder = new int[Sniper.SAVE_ARRAY_SIZE]; while (_snr.hasNext()) { try { this.readingString = _snr.nextLine(); final int _key = Integer.parseInt(this.readingString); this.readingBrush = this.myBrushes.get(_snr.nextLine()); this.brushPresets.put(_key, this.readingBrush); _presetsHolder[Sniper.SAVE_ARRAY_VOXEL_ID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_REPLACE_VOXEL_ID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_DATA_VALUE] = Byte.parseByte(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_BRUSH_SIZE] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_VOXEL_HEIGHT] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_CENTROID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_REPLACE_DATA_VALUE] = Byte.parseByte(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_RANGE] = Integer.parseInt(_snr.nextLine()); this.brushPresetsParams.put(_key, _presetsHolder); } catch (final NumberFormatException _e) { boolean _first = true; while (_snr.hasNext()) { String _keyS; if (_first) { _keyS = this.readingString; _first = false; } else { _keyS = _snr.nextLine(); } this.readingBrush = this.myBrushes.get(_snr.nextLine()); this.brushPresetsS.put(_keyS, this.readingBrush); _presetsHolder[Sniper.SAVE_ARRAY_VOXEL_ID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_REPLACE_VOXEL_ID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_DATA_VALUE] = Byte.parseByte(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_BRUSH_SIZE] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_VOXEL_HEIGHT] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_CENTROID] = Integer.parseInt(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_REPLACE_DATA_VALUE] = Byte.parseByte(_snr.nextLine()); _presetsHolder[Sniper.SAVE_ARRAY_RANGE] = Integer.parseInt(_snr.nextLine()); this.brushPresetsParamsS.put(_keyS, _presetsHolder); } } } _snr.close(); } } catch (final Exception _e) { _e.printStackTrace(); } }
// experimental // ==================================================================== // ==================================================================== // ==================================================================== private void readAndDrawBIGGraph(String file) { // behövs inte än // @TODO // hur rita flera linjer mellan 2 noder? (för flera linjer) // reading of the graph should be done in the graph itself // it should be possible to get an iterator over nodes and one over edges // read in all the stops and lines and draw the lmap Scanner indata = null; // insert into p-queue to get them sorted names = new PriorityQueue<String>(); try { // Read stops and put them in the node-table // in order to give the user a list of possible stops // assume input file is correct indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); // while (indata.hasNext()) { String hpl = indata.next().trim(); int xco = indata.nextInt(); int yco = indata.nextInt(); noderna.add(new BusStop(hpl, xco, yco)); names.add(hpl); // Draw // this is a fix: fixa att Kålltorp och Torp är samma hållplats if (hpl.equals("Torp")) { xco += 11; hpl = " / Torp"; } karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE); } indata.close(); // Read in the lines and add to the graph indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859"); grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes()); Color color = new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); // String lineNo = "1"; // while (indata.hasNext()) { // assume lines are correct int from = noderna.find(indata.next()).getNodeNo(); int to = noderna.find(indata.next()).getNodeNo(); grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo)); indata.nextLine(); // skip rest of line // Draw BusStop busFrom = noderna.find(from); BusStop busTo = noderna.find(to); karta.drawLine( busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE); } indata.close(); } catch (FileNotFoundException fnfe) { throw new RuntimeException(" Indata till busshållplatserna saknas"); } karta.repaint(); } // end readAndDrawBIGGraph
public static int initializeCentroids() throws FileNotFoundException { int i, k, index, numClust = 0; Review rv; String reviews = new String(); String singleRv = new String(); String reviewer = new String(); String rating = new String(); for (i = 0; i < maxClusters; i++) { centroids[i] = new Cluster(); centroids_ref[i] = new Cluster(); } File modelFile = new File(strModelFile); Scanner opnScanner = new Scanner(modelFile); while (opnScanner.hasNext()) { k = opnScanner.nextInt(); centroids_ref[k].similarity = opnScanner.nextFloat(); centroids_ref[k].movie_id = opnScanner.nextLong(); centroids_ref[k].total = opnScanner.nextShort(); // Leo centroids_ref[k].total = attrNum + 1; reviews = opnScanner.next(); Scanner revScanner = new Scanner(reviews).useDelimiter(","); // while(revScanner.hasNext()){ //Leo int attrCnt = 0; while (revScanner.hasNext() && attrCnt < attrNum) { singleRv = revScanner.next(); index = singleRv.indexOf("_"); // reviewer = new String(singleRv.substring(0,index)); //Leo reviewer = new String(String.valueOf(attrCnt)); rating = new String(singleRv.substring(index + 1)); rv = new Review(); rv.rater_id = Integer.parseInt(reviewer); rv.rating = (byte) Integer.parseInt(rating); centroids_ref[k].reviews.add(rv); attrCnt++; } } // implementing naive bubble sort as maxClusters is small // sorting is done to assign top most cluster ids in each iteration for (int pass = 1; pass < maxClusters; pass++) { for (int u = 0; u < maxClusters - pass; u++) { if (centroids_ref[u].movie_id < centroids_ref[u + 1].movie_id) { Cluster temp = new Cluster(centroids_ref[u]); centroids_ref[u] = centroids_ref[u + 1]; centroids_ref[u + 1] = temp; } } } for (int l = 0; l < maxClusters; l++) { if (centroids_ref[l].movie_id != -1) { numClust++; } } return numClust; }
private static String compileContent(InputStream stream) { String compiledContent = ""; Scanner s = new Scanner(stream); while (s.hasNext()) { compiledContent += s.next(); if (s.hasNext()) { compiledContent += " "; } } return compiledContent; }
/** * Originally designed for Iris plants, could be used for any thing that follows this file format * * <p>double, double, double, double, string * * <p>Phase takes a scanner and create a list of QuickSubject. * * @param scanner * @return */ public static List<QuickSubject> phase(Scanner scanner) { List<QuickSubject> li = new ArrayList<>(); scanner.useDelimiter(" "); mainLoop: while (scanner.hasNext()) { while (!scanner.hasNextDouble() && !scanner.hasNextFloat()) { scanner.next(); if (!scanner.hasNext()) { break mainLoop; // ends loop } } double sepalLength = scanner.nextDouble(); while (!scanner.hasNextDouble() && !scanner.hasNextFloat()) { scanner.next(); if (!scanner.hasNext()) { break mainLoop; } } double sepalWidth = scanner.nextDouble(); while (!scanner.hasNextDouble() && !scanner.hasNextFloat()) { scanner.next(); if (!scanner.hasNext()) { break mainLoop; } } double petalLength = scanner.nextDouble(); while (!scanner.hasNextDouble() && !scanner.hasNextFloat()) { scanner.next(); if (!scanner.hasNext()) { break mainLoop; } } double petalWidth = scanner.nextDouble(); if (!scanner.hasNextLine()) { break; } String label = scanner.nextLine().substring(1); // System.out.println(sepalLength+" "+sepalWidth+" "+petalLength+" "+petalWidth+" "+label); li.add(new QuickSubject(sepalLength, sepalWidth, petalLength, petalWidth, label)); } scanner.close(); return li; }
public static void main(String[] args) throws Exception { // accept argument to set threshold support and confidence int support = 3; double confidence = 0.65; int argsLength = args.length; if (argsLength >= 1) { if (argsLength >= 2) { support = Integer.parseInt(args[1]); if (argsLength >= 3) { confidence = Double.parseDouble(args[2]); confidence = confidence / 100; if (argsLength >= 4) { expandLevel = Integer.parseInt(args[3]); } } } } Scanner scanner = new Scanner(System.in); Pattern caller_p = Pattern.compile("Call.*'(.*)'.*"); Pattern callee_p = Pattern.compile(".*'(.*)'.*"); Matcher caller_m = null; Matcher callee_m = null; String line = null; while (scanner.hasNext()) { line = scanner.nextLine(); caller_m = caller_p.matcher(line); if (caller_m.matches() /*&& !"main".equals(caller_m.group(1))*/) { nearByCallees.clear(); Set<String> callees = new HashSet<String>(); while (scanner.hasNext()) { line = scanner.nextLine(); if (line.length() == 0) { break; } callee_m = callee_p.matcher(line); if (callee_m.matches()) { addValueToMap(callee_m.group(1), caller_m.group(1)); nearByCallees.add(callee_m.group(1)); callees.add(callee_m.group(1)); } } if (!callees.isEmpty()) { callerCallee.put(caller_m.group(1), callees); } } } scanner.close(); // Traverse HashMap 'location' and print bug printBug(support, confidence); }
private static String getInputFromUser(String question, String errorMessage, String pattern) { showUser(question); Scanner scanIn = new Scanner(System.in); while (scanIn.hasNext() && !scanIn.hasNext(pattern)) { scanIn.next(); showUser(errorMessage); } String returnValue = scanIn.next(pattern); return returnValue; }
@Override public CatBuildCommand command(String command) throws Exception { // magrit cat-build SHA1 Scanner s = new Scanner(command); s.useDelimiter("\\s{1,}"); check(s.next(), "magrit"); check(s.next(), "cat-build"); check(command, s.hasNext()); this.repository = createRepository(s.next()); check(command, s.hasNext()); checkSha1(sha1 = s.next()); return this; }
public void loadInputToModel() { Scanner in = new Scanner(this.input); String previous; if (in.hasNext()) { String current = in.next(); while (in.hasNext()) { previous = current; current = in.next(); this.model.addSourceDestination(previous, current); } } }
public void first() { // System.out.println("Inside First. This is called only once"); java.util.Scanner s = null; try { s = new java.util.Scanner(new java.io.BufferedReader(new java.io.FileReader("sample"))); s.useLocale(java.util.Locale.US); position = 0; while (s.hasNext()) { if (s.hasNextLine()) { String c = s.nextLine(); ch[position] = c.charAt(0); for (int i = 0; i < 35; i++) { Character cha = new Character(c.charAt(i + 1)); String st = cha.toString(); data[position][i] = Integer.parseInt(st); } position++; } } } catch (java.io.IOException ert) { javax.swing.JOptionPane.showMessageDialog( null, ert, "Error", javax.swing.JOptionPane.ERROR_MESSAGE); } try { s = new java.util.Scanner(new java.io.BufferedReader(new java.io.FileReader("imageload"))); s.useLocale(java.util.Locale.US); while (s.hasNext()) { if (s.hasNextLine()) { imagedir = s.nextLine(); } } } catch (java.io.IOException ert) { javax.swing.JOptionPane.showMessageDialog( null, ert, "Error", javax.swing.JOptionPane.ERROR_MESSAGE); } s.close(); if (imagedir.equals("")) { javax.swing.JOptionPane.showMessageDialog( null, "This must be your first run of Live! Character Recognition.\nPlease set an image folder.", "Problem loading image", javax.swing.JOptionPane.INFORMATION_MESSAGE); } else { im.running(); } }
private static boolean isInteger(String s, int radix) { Scanner sc = new Scanner(s.trim()); if (!sc.hasNextInt(radix)) return false; sc.nextInt(radix); return !sc.hasNext(); }
/** * readFileAndFillArray method. Receives a file and returns an ArrayList filled with the contents * of the file. * * @precondition The file has to exist. * @precondition All values should be positive. * @postcondition Array filled with pebble weights * @param String fileDir file containing the pebbles' weights * @param ArrayList<Pebbles> bagContentsPebble empty array representing one of the bags * @return ArrayList<Integer> bagContents the filled array representing one of the bags * @throws IllegalWeightException * @throws FileNotFoundException */ public static ArrayList<Pebbles> readFileAndFillArray( String fileDir, ArrayList<Pebbles> bagContentsPebble) throws IllegalWeightException, FileNotFoundException { // Get scanner instance Scanner scanner = new Scanner(new FileReader(fileDir)); // Set the delimiter used in file scanner.useDelimiter(","); // Get all tokens and store them a list while (scanner.hasNext()) { String value = scanner.next(); // convert to integer and get rid of extra space with trim int valueInt = Integer.parseInt(value.trim()); // check if the weight is valid if (valueInt >= 0) { bagContentsPebble.add(new Pebbles(valueInt)); } // if the weight is not valid -> warn the user else { scanner.close(); throw new IllegalWeightException(null); } } // Do not forget to close the scanner scanner.close(); return bagContentsPebble; }
public static LinkedList<String> readFromFile() { File f; Scanner scanner; LinkedList<String> result = new LinkedList<>(); try { f = new File(fileName); scanner = new Scanner(f); // Pattern regex = Pattern.compile("\\w"); while (scanner.hasNext()) { String current = scanner.next(); String[] splitLine = current.split(","); for (int i = 0; i < splitLine.length; i++) { // Debug statement System.out.println("Scanner adding to list:" + splitLine[i]); result.add(splitLine[i]); } System.out.println("Scanner reading:" + current); // result.add(current); // System.out.println("Output of file" + ); } return result; } catch (IOException exc) { System.out.println("Error reading file line" + exc.getMessage()); } return null; }
@Override public void run() { try { host = InetAddress.getLocalHost().getHostName(); s = new Socket(host, SERVER_PORT); output = new PrintWriter(s.getOutputStream(), true); input = new Scanner(s.getInputStream()); output.println(name); while (!s.isClosed()) { if (input.hasNext()) { String msg = input.nextLine(); if (msg.contains("!%#&")) { String tmp = msg.substring(4); tmp = tmp.replace("[", ""); tmp = tmp.replace("]", ""); String[] users = tmp.split(", "); activelist.setListData(users); } else { history.append(msg + "\n"); } } } } catch (IOException e) { System.out.println(e); JOptionPane.showMessageDialog(null, "Unable to connect to the server."); System.exit(0); } }
@Override public int corpusDocFrequencyByTerm(String term) { String indexFile = _options._indexPrefix + "/merge.txt"; try { BufferedReader reader = new BufferedReader(new FileReader(indexFile)); String line; while ((line = reader.readLine()) != null) { int termDocFren = 0; String title = ""; String data = ""; Scanner s = new Scanner(line).useDelimiter("\t"); while (s.hasNext()) { title = s.next(); data = s.next(); } if (title.equals(term)) { String[] docs = data.split("\\|"); termDocFren = docs.length; } reader.close(); return termDocFren; } reader.close(); } catch (Exception e) { e.printStackTrace(); } return 0; }
private int generateIndex(String content, int docid) { Scanner s = new Scanner(content); // Uses white space by default. int totalcount = 0; while (s.hasNext()) { ++_totalTermFrequency; ++totalcount; String token = s.next(); // decrement the size() by 1 as the real doc id // int did=_documents.size()-1; Vector<Integer> plist = _index.get(token); if (plist != null) { if (plist.lastElement() != docid) { plist.add(docid); _index.put(token, plist); } } else { // _terms.add(token); Vector<Integer> p = new Vector<Integer>(); p.add(docid); _index.put(token, p); } } return totalcount; }