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 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); } }
// 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) { 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(); }
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[]) throws Exception { Scanner cin = new Scanner(System.in); BigInteger s, M; int p, i; while (cin.hasNext()) { p = cin.nextInt(); s = BigInteger.valueOf(4); M = BigInteger.ONE; M = M.shiftLeft(p).subtract(BigInteger.ONE); for (i = 0; i < p - 2; ++i) { s = s.multiply(s).subtract(BigInteger.valueOf(2)); while (s.bitLength() > p) { s = s.shiftRight(p).add(s.and(M)); } } if (s.compareTo(BigInteger.ZERO) == 0 || s.compareTo(M) == 0) { System.out.println(0); continue; } String ans = ""; while (s.compareTo(BigInteger.ZERO) > 0) { long buf = s.mod(BigInteger.valueOf(16)).longValue(); ans += Integer.toHexString((int) buf); s = s.divide(BigInteger.valueOf(16)); } for (i = ans.length() - 1; i >= 0; --i) System.out.print(ans.charAt(i)); System.out.println(); } }
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(); }
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) { } }
/* Method: parseInputLine - text parser Purpose: parse the line of text and returns a TreeNode Parameters: String line the line of text being parsed Returns: Entry - the Object parsed from the text line */ private TreeNode parseInputLine(String line) { if (line.equals("")) { // returns a null object if the line is empty // only null entry source in code return null; } // a new empty TreeNode object TreeNode returnNode = new TreeNode(ENTRY); // is an entry // Scanner to scan the line of text Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("/"); // sets the entry's word returnNode.setMyString(lineScanner.next()); while (lineScanner.hasNext()) { // the next word in the line String nextWord = lineScanner.next(); // end of line and 'a//b/c' blank words if (!(nextWord == null) && !(nextWord.equals(""))) { // adds each word in alphabet order to the // synonym linkedList returnNode.addSynonymInOrder(nextWord); // might not have any synonyms } } // returns the finished entry object return returnNode; }
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 solve() { Scanner s = new Scanner(System.in); while (s.hasNext()) { int n = s.nextInt(); System.out.println(ci(n + 1)); } }
public static void main(String[] args) { try { Scanner scanner = new Scanner(new FileInputStream("graph.txt")); int v = Integer.parseInt(scanner.nextLine()); int source = Integer.parseInt(scanner.nextLine()); int sink = Integer.parseInt(scanner.nextLine()); ListGraph g = new ListGraph(v, source, sink); while (scanner.hasNext()) { String edgeLine = scanner.nextLine(); String[] components = edgeLine.split("\\s+"); assert components.length == 3; int i = Integer.parseInt(components[0]); int j = Integer.parseInt(components[1]); int capacity = Integer.parseInt(components[2]); g.addEdge(i, j, capacity); } System.out.println("Original matrix"); g.print(); ListGraph.maxFlow(g); g.print(); } catch (FileNotFoundException e) { System.err.println(e.toString()); System.exit(1); } }
/** Creates hashtable to store all the words in the dictionary */ public static void createHashTable() { try { Scanner fileReader = new Scanner(new File("largedictionary.txt")); // read in every word from the dictionary file while (fileReader.hasNext()) { String theWord = fileReader.next(); // create hash index for the word int index = toHash(theWord); // linear probing if the hashtable cell is occupied while (hashtable[index] != null) { index += 1; // if we somehow hit the end of the hashtable, go back to the beginning if (index == TABLE_SIZE) { index = 0; } } hashtable[index] = theWord; } } catch (FileNotFoundException e) { System.out.println("File not found."); } }
public static void main(final String[] args) throws FileNotFoundException { if (args.length == 0) { System.out.println(usage); return; } Scanner sc = new Scanner(new File(dictFile)); ArrayList<String> dict = new ArrayList<String>(); while (sc.hasNext()) { dict.add(sc.next()); } if (args[0].equals("list") && args.length == 2) { String word = args[1]; System.out.println(fmtList(wordLadder(word, dict))); } else if (args[0].equals("top") && args.length == 2) { int num = Integer.parseInt(args[1]); System.out.println(fmtPairs(mostLadderable(num, dict))); } else if (args[0].equals("chain") && args.length == 3) { int steps = Integer.parseInt(args[1]); List<String> start = new ArrayList<String>(); start.add(args[2]); Set<String> chain = wordChain(steps, start, dict); System.out.println(chain.size()); } else { System.out.println(usage); return; } }
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; }
public Editor(File file) throws FileNotFoundException { this.file = file; Scanner fileScanner = new Scanner(file); while (fileScanner.hasNext()) { text += fileScanner.nextLine() + '\n'; } }
public static void main(String[] args) { Scanner cin = new Scanner(System.in); int input; int[][] count = new int[10000][2]; int length = 0, flag = 0; while (cin.hasNext()) { boolean check = false; input = cin.nextInt(); for (int a = 0; a < length; a++) { if (check == false && input == count[a][0]) { check = true; flag = a; } if (check == true) { break; } } if (check == true) { count[flag][1]++; } if (check == false) { count[length][0] = input; count[length][1]++; length++; } } for (int b = 0; b < length; b++) { System.out.println(count[b][0] + " " + count[b][1]); } }
public static void main(String args[]) throws Exception { HashSet<String> hs = new HashSet<String>(); FileReader fr1 = new FileReader("sample.txt"); BufferedReader br = new BufferedReader(fr1); String s; while ((s = br.readLine()) != null) { hs.add(s); } fr1.close(); FileReader fr2 = new FileReader("input.txt"); br = new BufferedReader(fr2); while ((s = br.readLine()) != null) { Scanner ip = new Scanner(s); String word; while (ip.hasNext()) { word = ip.next(); if (hs.contains(word)) ; else System.out.print(word + " "); } } fr2.close(); }
public static void main(String[] args) { try { flraf = new FLRAF(28); sc = new Scanner(new File("btree/words.txt")); } catch (FileNotFoundException f) { System.out.println(f); } while (sc.hasNext()) flraf.write(sc.next()); System.out.println("Block 0: " + flraf.read(0)); System.out.println("Block 5643: " + flraf.read(5643)); System.out.println("Block 45406: " + flraf.read(45406)); sc = new Scanner(System.in); System.out.print("Another? > "); while (sc.nextLine().equalsIgnoreCase("y")) { System.out.print("Enter index to read > "); String s = sc.nextLine(); if (s.contains(",")) { Integer j = Integer.parseInt(s.substring(0, s.lastIndexOf(","))); Integer k = Integer.parseInt(s.substring(s.lastIndexOf(",") + 1)); String[] st = flraf.read(j, k); System.out.println("Blocks : " + j + " - " + k + " : "); for (int i = 0; i < st.length; i++) if (st[i] != null) System.out.println(st[i]); else System.out.println("Index out of range"); } else { Integer i = Integer.parseInt(s); s = flraf.read(i); if (s != null) System.out.println("Block " + i + ": " + s); else System.out.println("Index out of range"); } System.out.print("Another?"); } }
/** * reads faculty list file * * @return LinkedList<Faculty> * @throws FileNotFoundException */ public LinkedList<Faculty> readFacultyList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("facultyList.csv"); LinkedList<Faculty> facultyList = new LinkedList<Faculty>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates faculty member Faculty newFaculty = new Faculty(userName, password, email, firstName, lastName, office, phoneNumber); facultyList.add(newFaculty); } fstream.close(); } catch (Exception e) { facultyList = null; } Collections.sort(facultyList); return facultyList; }
/** * The read admin list reads in admin objects from a readfile * * @return * @throws FileNotFoundException */ public LinkedList<Admin> readAdminList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("adminList.csv"); LinkedList<Admin> adminList = new LinkedList<Admin>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates admin Admin newAdmin = new Admin(userName, password, email, firstName, lastName, office, phoneNumber); adminList.add(newAdmin); } fstream.close(); } catch (Exception e) { adminList = null; } Collections.sort(adminList); return adminList; }
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()); } }
public static void main(String[] args) throws Exception { Scanner s = new Scanner(new FileReader("pb.in")); while (s.hasNext()) { String line = s.nextLine(); String[] rep = line.split("\\("); String[] nonrep = (rep[0] + "0").split("\\."); long num1 = Integer.parseInt(rep[1].substring(0, rep[1].length() - 1)); String nine = ""; while (nine.length() != rep[1].length() - 1) nine += "9"; for (int i = 0; i < nonrep[1].length() - 1; i++) nine += "0"; String ten = ""; while (nonrep[1].length() != ten.length()) ten += "0"; ten = "1" + ten; String nr = nonrep[0] + nonrep[1]; long den1 = Long.parseLong(nine); long den2 = Long.parseLong(ten); long num2 = Long.parseLong(nr); long num = num1 * den2 + num2 * den1; long den = den1 * den2; long gcd = new BigInteger("" + num).gcd(new BigInteger("" + den)).longValue(); num /= gcd; den /= gcd; System.out.println(line + " = " + num + " / " + den); } }
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(); }
/** Reads in the letter location data for the word hunt puzzle */ public static void readPuzzle() { letters = new String[3][3][2]; try { Scanner reader = new Scanner(new File("graph.txt")); while (reader.hasNext()) { String temp = reader.next(); // if the String is not a number it is a character if (!NUMBERS.contains(temp)) { // find the coordinates of the letter/String int x = reader.nextInt(); int y = reader.nextInt(); int z = reader.nextInt(); letters[x][y][z] = temp; } } // prints out the word hunt set up, in separate squares that represent the 2D arrays at each // depth for (int k = 0; k < 2; k++) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(letters[i][j][k] + " "); } System.out.print("\n"); } System.out.print("\n"); } } catch (FileNotFoundException e) { System.out.println("No such file."); } }
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(); } }
/** * @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 LinkedList<profile> importer() throws IOException { LinkedList<profile> people = new LinkedList<profile>(); Scanner sFile; profile entry; try { sFile = new Scanner(new File("/Users/richarddavies/NetBeansProjects/typ_MatlabGraph/users.dat")); sFile.nextLine(); while (sFile.hasNext()) { String profile = sFile.nextLine(); // System.out.println(profile); Scanner profScan = new Scanner(profile); profScan.useDelimiter(","); while (profScan.hasNext()) { Long id = profScan.nextLong(); String ident = String.valueOf(id); String rot_Id = rot13.encrypt(ident); Long rot_IntId = Long.parseLong(rot_Id); String fname = profScan.next(); String rot_Name = rot13.encrypt(fname); // String sname = profScan.next(); // int age = profScan.nextInt(); String gender = profScan.next(); String nat = profScan.next(); entry = new profile(id, fname, gender, nat); // System.out.println("id: "+id+" name: "+fname+" gender: "+gender+" nationality: "+nat); // System.out.println("id: "+rot_IntId+" name: "+rot_Name+" gender: "+gender+" // nationality: "+nat); people.add(entry); } } } catch (IOException ex) { // return people; System.out.println("(No System File profile.txt)" + ex); } return people; }
private List<String> scan(Scanner scanner) { List<String> strings = new LinkedList<String>(); while (scanner.hasNext()) { String string = scanner.next(); if (isComment(string)) continue; strings.add(string); } return strings; }
// Gets all messages and returns as a ArrayList public ArrayList<String> getAllMessages() { ArrayList<String> messages = new ArrayList<>(); while (input.hasNext()) { messages.add(input.nextLine()); } return messages; }