public static int[][] getData(String fileName) { Vector<String> dataSet = new Vector<String>(); String oneLine = ""; int[][] data = new int[1][1]; try { Scanner sc = new Scanner(new File(fileName)); while (sc.hasNextLine()) { oneLine = sc.nextLine(); dataSet.add(oneLine); } sc.close(); int row = dataSet.size() - 1; data = new int[row][2]; for (int i = 1; i < row + 1; i++) { sc = new Scanner(dataSet.elementAt(i)).useDelimiter(" "); data[i - 1][1] = sc.nextInt(); for (int j = 0; j < 2; j++) { sc.next(); } data[i - 1][0] = sc.nextInt(); sc.close(); } sc.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } return data; }
public static void main(String[] args) { if (args.length < 2) throw new IllegalArgumentException("Not enough arguments present on initial program run"); LinkedList<LinkedList<Anagram>>[] dictList = new LinkedList[199967]; int wordCount = 0, collisions = 0; Scanner dictScanner = createInputScanner("words.txt"); Scanner queryScanner = createInputScanner(args[0]); PrintWriter fout = createPrintWriter(args[1]); Pattern matchMaker = Pattern.compile("[A-Za-z0-9]+"); while (dictScanner.hasNext()) { String line = dictScanner.nextLine(); if (matchMaker.matcher(line).matches()) { collisions += hashStash(line, dictList); wordCount++; } } hashQuery(dictList, queryScanner, fout); /* for(int i = 0; i < dictList.length; i++){ if(dictList[i] != null){ fout.println(dictList[i].toString()); System.out.print(dictList[i].size()); } }*/ System.out.println("Words: " + wordCount + " Collisions:" + collisions); fout.close(); dictScanner.close(); queryScanner.close(); }
// 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 void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); int tIndex = 0; int pIndex = 0; // This will probably change soon (name and implementation) NgramParser tnp = new NgramParser(args[1]); ArrayList<String> triplet = tnp.getTriplet(); ArrayList<String> polarity = tnp.getPolarity(); FileWriter sw = new FileWriter(args[2]); String line = null; while (((line = br.readLine()) != null) && (tIndex < triplet.size()) && (pIndex < polarity.size())) { if (line.matches("^[\\d]*:")) { // System.out.println(line); sw.write(line + "\n"); } else { Scanner sc = new Scanner(line); String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*")); // if (trip != null && trip.equals(triplet.get(tIndex))) { System.out.println(trip); if (trip != null && !trip.toLowerCase().contains("no#cl")) { // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex)); String pol = polarity.get(pIndex); sw.write(line + " " + pol + "\n"); sc.close(); tIndex++; pIndex++; } else { String pol = "neg"; sw.write("no#a#1" + " " + pol + "\n"); sc.close(); } } // sw.flush(); } sw.close(); } catch (IOException e) { e.printStackTrace(); } }
private static boolean getNumberOfLines(File file, int total, float mean) { try { double difSum = 0; long last, actual; int nLines = 0; Scanner scan = new Scanner(file); scan.useLocale(Locale.US); if (scan.hasNextLine()) { scan.nextLine(); if (scan.hasNextLong() && scan.hasNextLine()) { last = scan.nextLong(); nLines++; scan.nextLine(); } else { scan.close(); return false; } } else { scan.close(); return false; } while (scan.hasNextLong()) { actual = scan.nextLong(); nLines++; difSum += actual - last; last = actual; if (scan.hasNextLine()) { scan.nextLine(); } else { break; } } scan.close(); total = nLines; mean = (float) difSum / (total - 1); return true; } catch (FileNotFoundException e1) { return false; } }
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 void readFileAsList() throws IOException, DictionaryException { BufferedReader br; StringTokenizer tz; for (int i = 0; i < files.length; i++) { List<String> words = new ArrayList<String>(); String wordLine = ""; String[] word; Scanner file = new Scanner(new FileReader(files[i])); while (file.hasNext()) wordLine += file.nextLine().toLowerCase(); file.close(); word = wordLine.split("[?!*,-.\"_\"\\;/:)(+\\s]+"); for (int j = 0; j < word.length; j++) { words.add(word[j]); } StopWords stopWords = new StopWords(); words = StopWords.removeStopWords(words); /*for (int j = 0; j < words.size(); j++) { System.out.print(words.get(j) + "/"); }*/ write(words, files[i].getName()); } }
static void make_text_table() { try { Scanner in = new Scanner(new FileReader("ciphertext.txt")); String str; text = new String[1000]; text_index = 0; while (in.hasNext()) { str = in.next(); int start = 0; int fin = 0; // System.out.println(str); while (fin <= str.length()) { // word parsing from start to fin if (fin == str.length() || str.charAt(fin) < 'a' || str.charAt(fin) > 'z') { String substr = str.subSequence(start, fin).toString(); // System.out.println(substr); int i; for (i = 0; i < text_index; i++) if (text[i].equals(substr)) break; if (i == text_index & substr.length() > 0) text[text_index++] = new String(substr); start = fin + 1; } fin++; } } // for(int i=0;i<text_index;i++)System.out.println(text[i]); // System.out.println(text_index); in.close(); } catch (FileNotFoundException r) { } }
public void init() { Scanner scan = new Scanner(System.in); count = scan.nextInt(); x0 = scan.nextLong(); y0 = scan.nextLong(); int result = 0; boolean special = false; for (int i = 0; i < count; i++) { long tempx = scan.nextLong(); long tempy = scan.nextLong(); if (tempx == x0 && tempy == y0) { special = true; continue; } boolean isDuplicate = false; for (int j = 0; j < result; j++) { long x1 = xList.get(j); long y1 = yList.get(j); if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) { isDuplicate = true; break; } } if (!isDuplicate) { xList.add(tempx); yList.add(tempy); result++; } } if (special && result == 0) result = 1; System.out.println(result); scan.close(); }
/** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub System.out.println("Swim Meet Planner"); // scanner to read file Scanner fileReader = new Scanner(new File("src/Finalprojectinput")); // create results Map HashMap<String, ArrayList<Integer>> results = new HashMap<String, ArrayList<Integer>>(); // adding names and times to results Map while (fileReader.hasNext()) { String name = fileReader.next(); int time = fileReader.nextInt(); // does swimmer exist in map? if (results.containsKey(name)) { results.get(name).add(time); } else { ArrayList<Integer> times = new ArrayList<Integer>(); times.add(time); results.put(name, times); } } fileReader.close(); Average a = new Average(); a.average(results); }
public static String openFile(String nameProgram) throws FileNotFoundException { Scanner scanner = new Scanner(new File(nameProgram)); String programString = ""; while (scanner.hasNext()) programString += scanner.next(); scanner.close(); return programString; }
private static void patchConfFile(File originalConf, File dest, String library) throws IOException { Scanner sc = new Scanner(originalConf); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest))); try { boolean patched = false; while (sc.hasNextLine()) { String line = sc.nextLine(); out.append(line); out.newLine(); if (!patched && "[plexus.core]".equals(line)) { out.append("load ").append(library); out.newLine(); patched = true; } } } finally { out.close(); } } finally { sc.close(); } }
// Slice data file in the constructor public PokemonCollection() { Scanner inFile; // Try and catch the IOException try { inFile = new Scanner(new BufferedReader(new FileReader("resources/pokemon.txt"))); } catch (IOException e) { System.out.println("Could not loadfile 'resources/pokemon.txt'!"); System.exit(-1); // Exit program if file could not be found return; } // Create a Pokemon[] based on the number of Pokemon int pokeNum = inFile.nextInt(); Pokemon[] pokemon = new Pokemon[pokeNum]; inFile.nextLine(); // Skip to next line for (int i = 0; i < pokeNum; i++) { // Pass string to processLine method processLine(inFile.nextLine()); } inFile.close(); }
public static void main(String[] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileReader("Lab3_input.txt")); PrintWriter outFile = new PrintWriter("Lab3_Exercise_output.txt"); // Declare variables String lastName, firstName; double salary, pctRaise, salaryFinal; // set up while loop while (inFile.hasNext()) // condition checks to see if there is anything in the input file { // Read information from input file lastName = inFile.next(); firstName = inFile.next(); salary = inFile.nextDouble(); pctRaise = inFile.nextDouble(); // Calculate final salary salaryFinal = salary + (salary * pctRaise / 100); // Write file outFile.printf("%s %s %.2f%n", lastName, firstName, salaryFinal); } // Close input/output methods outFile.close(); inFile.close(); }
public static void main(String[] args) { int i = 4; double d = 4.0; String s = "HackerRank "; Scanner scan = new Scanner(System.in); /* Declare second integer, double, and String variables. */ int j; double e; String t; /* Read and save an integer, double, and String to your variables.*/ j = scan.nextInt(); e = scan.nextDouble(); scan.nextLine(); t = scan.nextLine(); /* Print the sum of both integer variables on a new line. */ System.out.println(i + j); /* Print the sum of the double variables on a new line. */ System.out.println(d + e); /* Concatenate and print the String variables on a new line; the 's' variable above should be printed first. */ System.out.println(s + t); scan.close(); }
/** * Opens a file. If the file can be opened, get a drawing time estimate, update recent files list, * and repaint the preview tab. * * @param filename what file to open */ public void LoadGCode(String filename) { CloseFile(); try { Scanner scanner = new Scanner(new FileInputStream(filename)); linesTotal = 0; gcode = new ArrayList<String>(); try { while (scanner.hasNextLine()) { gcode.add(scanner.nextLine()); ++linesTotal; } } finally { scanner.close(); } } catch (IOException e) { Log("<span style='color:red'>File could not be opened.</span>\n"); RemoveRecentFile(filename); return; } previewPane.setGCode(gcode); fileOpened = true; EstimateDrawTime(); UpdateRecentFiles(filename); Halt(); }
public static void main(String[] args) { // obtain user's choice // String input = JOptionPane.showInputDialog( // "Enter 1 to draw rectangles\n" + // "Enter 2 to draw ovals" ); // // int choice = Integer.parseInt( input ); // convert input to int // added by Zhang int choice = 1; Scanner input; try { input = new Scanner(new File("Input.txt")); choice = input.nextInt(); input.close(); } catch (IOException e) { System.err.println(e); System.exit(1); } // end of addition by Zhang // create the panel with the user's input // Shapes panel = new Shapes( choice ); Shapes panel = new Shapes(choice); JFrame application = new JFrame("Shapes"); // creates a new JFrame application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(panel); // add the panel to the frame application.setSize(300, 300); // set the desired size application.setVisible(true); // show the frame } // end main
public void load(File target) { try { Scanner input = new Scanner(target); // Loads in the initial information, resets some values, such as scores, as well sideLength_ = input.nextInt(); currentPlayer_ = input.nextInt(); board_ = new int[sideLength_][sideLength_]; totalMovesPossible_ = (sideLength_ - 2) * (sideLength_ - 2) - 4; p1Score_ = 0; p2Score_ = 0; emptySpacesLeft_ = 0; input.nextLine(); // Extra nextLine method to get past the first two lines for (int y = 0; input.hasNextLine(); y++) { String[] stringLine = input.nextLine().split(valueSeparator_); for (int x = 0; x < stringLine.length; x++) { int value = Integer.parseInt(stringLine[x]); board_[x][y] = value; if (value == 1) { p1Score_++; } else if (value == 2) { p2Score_++; } else if (value == 0) { emptySpacesLeft_++; } } } input.close(); } catch (Exception e) { System.out.println(e); } }
public static void main(String[] args) throws IOException { if (args.length < 2) { System.out.println("Usage: WordSort inputfile outputfile"); return; } String inputfile = args[0]; String outputfile = args[1]; /* Create the word map. Each key is a word and each value is an * Integer that represents the number of times the word occurs * in the input file. */ Map<String, Integer> map = new TreeMap<String, Integer>(); // read every line of the input file Scanner scanner = new Scanner(new File(inputfile)); while (scanner.hasNext()) { String word = scanner.next(); Integer count = map.get(word); count = (count == null ? 1 : count + 1); map.put(word, count); } scanner.close(); // get the map's keys List<String> keys = new ArrayList<String>(map.keySet()); // write the results to the output file PrintWriter out = new PrintWriter(new FileWriter(outputfile)); for (String key : keys) { out.println(key + " : " + map.get(key)); } out.close(); }
public static void main(String[] args) throws IOException { in = new Scanner(new FileReader("wordFreq.in")); out = new PrintWriter(new FileWriter("wordFreq.out")); WordInfo[] wordTable = new WordInfo[N + 1]; for (int h = 1; h <= N; h++) wordTable[h] = new WordInfo(); int first = -1; // points to first word in alphabetical order int numWords = 0; in.useDelimiter("[^a-zA-Z]+"); while (in.hasNext()) { String word = in.next().toLowerCase(); int loc = search(wordTable, word); if (loc > 0) wordTable[loc].freq++; else // this is a new word if (numWords < MaxWords) { // if table is not full first = addToTable(wordTable, word, -loc, first); ++numWords; } else out.printf("'%s' not added to table\n", word); } printResults(wordTable, first); in.close(); out.close(); } // end main
public void listaKargatu() { try { Scanner fitxategia = new Scanner(new FileReader(fitxategiarenHelbidea())); String linea; System.out.println(); System.out.println(); System.out.println("Datuak kargatzen diren bitartean itxaron..."); while (fitxategia.hasNext()) { linea = fitxategia.nextLine(); String[] items = linea.split("\\s*###\\s*"); Aktore nireAktorea = new Aktore(items[0]); for (int i = 1; i < items.length; i++) { if (!listaP.contains(items[i])) { Pelikula nirePelikula = new Pelikula(items[i]); listaP.addHash(items[i], nirePelikula); nireAktorea.gehituPelikula(nirePelikula); nirePelikula.geituAktore(nireAktorea); } else { nireAktorea.gehituPelikula(listaP.getPeli(items[i])); listaP.getPeli(items[i]).geituAktore(nireAktorea); ; } } listaA.gehituAktorea(nireAktorea); } fitxategia.close(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter name of the file: "); String a = input.next(); File file = new File(a); if (!file.exists()) { System.out.println("The file does not exist"); System.exit(1); } double sum = 0; double count = 0; double avg = 0; try { Scanner input2 = new Scanner(file); while (input2.hasNext()) { double score = input2.nextDouble(); sum = sum + score; count++; } } catch (Exception e) { System.out.println("Error!"); } avg = sum / count; System.out.println("Total scores: " + count); System.out.println("Sum of all scores: " + sum); System.out.println("Average of all scores: " + avg); input.close(); }
private String getProductPath(String jsonProductFileName) { String res = ""; Scanner fin = null; try { fin = new Scanner(new File(jsonProductFileName)); int countLines = 0; while (fin.hasNextLine()) { String str = fin.nextLine(); if (str.indexOf("path") >= 0) { int start_pos = str.indexOf("products"); int end_pos = str.lastIndexOf("\","); res = str.substring(start_pos, end_pos); break; } } } catch (FileNotFoundException ex) { } finally { if (null != fin) { fin.close(); fin = null; } } return res; }
/** Close the current Scanner object */ public void closeLink() { try { input.close(); } catch (NullPointerException e) { System.err.println(" Scanner not assigned"); } }
public void init() { Scanner scan = new Scanner(System.in); n = scan.nextInt(); m = scan.nextInt(); for (int i = 0; i < n; i++) { String input = scan.next(); record.add(input); } for (int i = 0; i < m; i++) { String input = scan.next(); char[] charArray = input.toCharArray(); boolean isValid = false; for (int j = 0; j < charArray.length; j++) { char c = charArray[j]; for (char d = 'a'; d <= 'c'; d = (char) (d + 1)) { if (d == c) continue; charArray[j] = d; if (record.contains(new String(charArray))) { isValid = true; break; } } charArray[j] = c; if (isValid) break; } if (isValid) System.out.println("YES"); else System.out.println("NO"); } scan.close(); }
public static void processFile_RNA(File f) { if (f == null || !f.exists()) return; if (f.isDirectory()) { processDir(f); return; } display("[Processing: " + f.getAbsolutePath() + "\n\n"); try { Scanner scan = new Scanner(f); String[] arr = new String[4]; int count = 0; while (scan.hasNextLine() && count < 4) { arr[count++] = scan.nextLine(); } scan.close(); if (arr[1] != null && arr[2] != null) { Map<String, StringBuilder> ht = parseNative(arr[1]); double[] vals = parsePredicted(arr[2], ht); String header = "Native Structure vs. MFE Predicted Structure\n" + "--------------------------------------------\n"; printCalculations(vals, header); if (arr[3] != null) { vals = parsePredicted(arr[3], ht); header = "Native Structure vs. Custom Predicted Structure\n" + "-----------------------------------------------\n"; printCalculations(vals, header); } } } catch (Exception e) { e.printStackTrace(); } }
public static String requestName() { Scanner keyboard = new Scanner(System.in); System.out.print("Name: "); String name = keyboard.nextLine(); keyboard.close(); return name; }
public static void main(String[] args) throws FileNotFoundException { InputStream in = new FileInputStream(new File("beads.in")); Scanner x = new Scanner(in); PrintWriter p = new PrintWriter("beads.out"); int n = x.nextInt(); String beads = x.next(); byte[] b = beads.getBytes(); char[] necklace = new char[2 * n]; for (int k = 0; k < 2 * n; k++) { if (k > n - 1) { necklace[k] = (char) b[k - n]; } else { necklace[k] = (char) b[k]; } } int sum = 0; int max = 0; int z, y; for (int i = 0; i < n; i++) { z = front(i, n, necklace); y = back(i, n, necklace); sum = z + y; if (max < sum) { max = sum; } } x.close(); if (max > n) max = n; p.println(max); p.close(); }
/** * Build Sample Method. Builds a simulation of a biological sample. Data is read in from a file to * create the sample, then the sample simulation data is stored in the two dimensional arrays: * Dish, DishCur, and DishFut. * * @param No Parameters * @return void - Does not return a value * @exception FileNotFoundException */ public void buildSample() throws FileNotFoundException { try { Scanner InFile = new Scanner(new File(this.Input)); this.Gen = InFile.nextInt(); for (int i = 0; i < MaxK; i++) { this.D[i] = InFile.nextInt(); } for (int r = 0; r < LoopBounds; r++) { for (int c = 0; c < LoopBounds; c++) { this.Dish[r][c] = InFile.nextInt(); } } InFile.close(); for (int r = 0; r < LoopBounds; r++) { for (int c = 0; c < LoopBounds; c++) { DishCur[r][c] = this.Dish[r][c]; } } for (int r = 0; r < LoopBounds; r++) { for (int c = 0; c < LoopBounds; c++) { DishFut[r][c] = DishCur[r][c]; } } } catch (Exception E) { System.out.println("Something went wrong reading from file"); } }
public void run() throws IOException { Scanner in = new Scanner(new File("partitions.in")); PrintWriter out = new PrintWriter(new File("partitions.out")); int sum = 0; while (true) { int n = in.nextInt(); sum += n; int k = in.nextInt(); if (n == 0 && k == 0) { break; } in.nextLine(); ArrayList<Integer>[] set = new ArrayList[k]; for (int i = 0; i < k; i++) { set[i] = new ArrayList<Integer>(); String t = in.nextLine(); Scanner sc = new Scanner(t); while (sc.hasNextInt()) { int q = 0; set[i].add(q = sc.nextInt() - 1); } } ArrayList<Integer> free = new ArrayList<Integer>(); int keep = 0; for (int i = k - 1; i >= 0; i--) { ArrayList<Integer> nxt = next(set[i], free); if (nxt != null) { set[i] = nxt; keep = i + 1; break; } else { free.addAll(set[i]); Collections.sort(free); } } int newk = keep + free.size(); out.println(n + " " + newk); for (int i = 0; i < keep; i++) { for (int j = 0; j < set[i].size(); j++) { if (j > 0) { out.print(" "); } out.print(set[i].get(j) + 1); } out.println(); } Collections.sort(free); for (int i = 0; i < free.size(); i++) { out.println(free.get(i) + 1); } out.println(); } assert sum <= 2000; in.close(); out.close(); }