/** * 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; }
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 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 main(String[] args) throws FileNotFoundException { /* Loads the word list and stores its length */ String ext = "/afs/cats/courses/cmps109-db/cmps012a-pa1/wordList.txt"; Scanner in = new Scanner(new FileInputStream(ext)); int listSize = in.nextInt(); // length of the word list /* Randomly selects word from the word list */ Random rand = new Random(); int n = rand.nextInt(listSize) + 1; for (int i = 1; i < n; i++) in.next(); String word = in.next(); /* Displays to the user the number of letters in the word */ System.out.println("Your word is " + word.length() + " letters long."); /* Recursive method that plays the game. TRUE return indicates win */ if (play(word)) { System.out.println("You win! The word was " + word + "."); } else { // Display for if the user loses System.out.println("You lose. The word was " + word + "."); } }
public static void main(String[] args) throws IOException { // Instantiate Objects FileReader fr = new FileReader("Accounts.txt"); PrintWriter pw = new PrintWriter("CurrentAccounts.txt"); Scanner console = new Scanner(fr); // Pull information from Accounts.txt into Strings String fullName = console.next(); String lastName = fullName.substring(0, 9); String firstName = fullName.substring(10, 17); String accountBalance = console.next(); String sWholeValue = accountBalance.substring(0, 4); String sDecimalValue = accountBalance.substring(5, 8); // Convert accountBalance from one string variable into two integer variables int wholeValue = Integer.parseInt(sWholeValue); int decimalValue = Integer.parseInt(sDecimalValue); // Write pw.printf("%15s %14s%06d%06d", firstName, lastName, wholeValue, decimalValue); // Close Streams fr.close(); pw.close(); }
public static void main(String[] args) { Scanner inp = new Scanner(System.in); int n = inp.nextInt(); String[] store = new String[n]; for (int i = 0; i < n; i++) store[i] = inp.next(); int[] cnt = new int[n]; Arrays.fill(cnt, 0); String str = inp.next(); for (int j = 0; j < n; j++) { int l1 = store[j].length(); for (int k = 0; k <= (str.length() - l1); k++) { if (str.substring(k, k + l1).equals(store[j])) { cnt[j] = cnt[j] + 1; } } } int y = 0; for (int m = 0; m < n; m++) { y = Math.max(y, cnt[m]); } System.out.println(y); for (int h = 0; h < n; h++) { if (cnt[h] == y) System.out.println(store[h]); } }
/* 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 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(); }
private static String checkString(Func function, Scanner input, boolean newAccount, UserID uid) { String str = ""; boolean valid = false; while (!valid) { if (function == Func.USERNAME) { if (newAccount) { System.out.println("Please enter your new username: "******"Please enter your user name"); } str = input.next(); valid = checkUserName(str, newAccount); } else if (function == Func.PASSWORD) { System.out.println("Please enter your password: "******"Please enter your first name: "); str = input.next(); valid = str.length() > 2; } if (!valid && !newAccount) return null; } return !valid ? null : str; }
public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File("gift1.in")); PrintWriter out = new PrintWriter(new FileWriter("gift1.out")); int people = s.nextInt(); HashMap<String, Integer> moneyGiven = new HashMap<String, Integer>(); HashMap<String, Integer> moneyReceived = new HashMap<String, Integer>(); String[] names = new String[people]; for (int x = 0; x < people; x++) { String name = s.next(); names[x] = name; moneyGiven.put(name, 0); moneyReceived.put(name, 0); } for (int x = 0; x < people; x++) { String person = s.next(); int give = s.nextInt(); int receivers = s.nextInt(); if (receivers == 0) continue; give = give - give % receivers; moneyGiven.put(person, give); for (int y = 0; y < receivers; y++) { String name = s.next(); moneyReceived.put(name, give / receivers + moneyReceived.get(name)); } } for (int x = 0; x < people; x++) { out.println(names[x] + " " + (moneyReceived.get(names[x]) - moneyGiven.get(names[x]))); } out.close(); }
/** * 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 static void main(String[] args) { Scanner input = new Scanner(System.in); int year = 0; String gender = ""; boolean boo = true; while (boo) { try { System.out.print("Enter year(must be 1880 or later): "); year = input.nextInt(); if (year > 1879) { boo = false; } } catch (InputMismatchException e) { System.out.println("Wrong input. Try again."); input.nextLine(); } } boo = true; while (boo) { try { System.out.print("Enter gender(M or F): "); gender = input.next(); if (gender.equals("M") || gender.equals("F")) { boo = false; } } catch (InputMismatchException e) { System.out.println("Wrong input. Try again."); input.nextLine(); } } boo = true; System.out.print("Enter name: "); String name = input.next(); File file = new File("babynamesranking" + year + ".txt"); if (!file.exists()) { System.out.println("File does not exist or there is no data for that year."); System.exit(1); } int rank = 0; try (Scanner input2 = new Scanner(file)) { while (input2.hasNextLine()) { int ranking = input2.nextInt(); String maleName = input2.next(); String femaleName = input2.next(); if (maleName.equals(name) || femaleName.equals(name)) { rank = ranking; } } input2.close(); } catch (Exception e) { System.out.println("Error"); } if (rank == 0) { System.out.println("The name is not ranked in this year."); } else System.out.println(name + " is ranked " + "#" + rank + " in year " + year); }
// Reads name popularity rank data from text file into HashMap public void readRankData(Scanner input) { while (input.hasNextLine()) { String dataLine = input.nextLine(); Person entry = new Person(dataLine); Scanner tokens = new Scanner(dataLine); String nameGender = tokens.next(); nameGender += tokens.next(); persons.put(nameGender, entry); } }
public static void main(String[] args) { Scanner s = new Scanner(System.in); try { s = new Scanner(new BufferedReader(new FileReader("system.properties"))); } catch (IOException e) { e.printStackTrace(); } s.useDelimiter("\\n|="); s.next(); int n = s.nextInt(); s.next(); int m = s.nextInt(); int[] stime = new int[n]; int[] otime = new int[n]; int k = 0; while (s.hasNext()) { s.next(); stime[k] = s.nextInt(); s.next(); otime[k] = s.nextInt(); k++; } FileWriter report = null; try { report = new FileWriter("output.log", false); } catch (IOException h) { } FileWriter event = null; try { event = new FileWriter("event.log", false); } catch (IOException g) { } Start.out = new PrintWriter(report); PrintWriter ev = new PrintWriter(event); Tree t = new Tree(n); TreeVisitor[] p = new TreeVisitor[n]; String times = ""; for (int i = 0; i < n; i++) p[i] = new TreeVisitor(n + i, m, t, stime[i], otime[i]); for (int i = 0; i < n; i++) p[i].start(); for (int i = 0; i < n; i++) { try { p[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } ev.println("sequence:\n"); ev.print(Start.runtimes); Start.out.close(); ev.close(); }
public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter the area of the circle here: "); double area = keyboard.nextDouble(); System.out.println("The radius of the circle is: " + Math.sqrt(area / Math.PI)); System.out.print("What is your fist name? "); String first = keyboard.next(); System.out.print("What is your last name? "); String last = keyboard.next(); System.out.println("Your full name is " + first + " " + last); }
// 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 ciphers(String message, int cipher, int encrypt_decrypt) { // determines which function to use depending on user input if (cipher == 1) { // asks user for a key System.out.println("Enter a key value: "); int k = cin.nextInt(); if (encrypt_decrypt == 1) { shift(message, k); } else { shift(message, -k); } } else if (cipher == 2) { // asks user for a key System.out.println("Enter a key value: "); int k = cin.nextInt(); // asks user for 'b' value System.out.println("Enter a 'b' value: "); int b = cin.nextInt(); if (encrypt_decrypt == 1) { affine(message, k, b, 1); } else { affine(message, k, b, 2); } } else if (cipher == 3) { // asks user for a keyword & gets rid of repeated characters System.out.println("Enter a keyword: "); String keyword = cin.next(); keyword = keyword.toUpperCase(); keyword = keyword.replaceAll( (String.format("(.)(?<=(?:(?=\\1).).{0,%d}(?:(?=\\1).))", keyword.length())), ""); if (encrypt_decrypt == 1) { substitution(message, keyword, 1); } else { substitution(message, keyword, 2); } } else if (cipher == 4) { // asks user for a keyword System.out.println("Enter a keyword: "); String keyword = cin.next(); keyword = keyword.toUpperCase(); if (encrypt_decrypt == 1) { vigenere(message, keyword, 1); } else { vigenere(message, keyword, 2); } } }
public static void main(String args[]) throws Exception { Scanner scn = new Scanner(System.in); youtubedl obj = new youtubedl(new URL(args[0])); obj.GetDownloadIndex(); obj.displayIndex(); System.out.print("Enter Index: "); String get_index = scn.next(); System.out.print("Enter Name: "); String get_name = scn.next(); obj.download(get_index, get_name); System.out.println(); }
/** * A partir de uma string com o conteudo de um form submetido no formato * application/x-www-form-urlencoded, devolve um objecto do tipo Properties, associando a cada * elemento do form o seu valor */ public static Properties parseHttpPostContents(String contents) throws IOException { Properties props = new Properties(); Scanner scanner = new Scanner(contents).useDelimiter("&"); while (scanner.hasNext()) { Scanner inScanner = new Scanner(scanner.next()).useDelimiter("="); String propName = URLDecoder.decode(inScanner.next(), "UTF-8"); String propValue = ""; try { propValue = URLDecoder.decode(inScanner.next(), "UTF-8"); } catch (Exception e) { // do nothing } props.setProperty(propName, propValue); } return props; }
public static void main(String args[]) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ Scanner in = new Scanner(System.in); int n = in.nextInt(); SuperStack stack = new SuperStack(); PrintWriter out = new PrintWriter(System.out, true); for (int i = 0; i < n; i++) { String s = in.next(); if (s.equals("push")) { int value = in.nextInt(); out.println(stack.push(value)); } else if (s.equals("pop")) { int res = stack.pop(); if (stack.size == 0) { out.println("EMPTY"); } else { out.println(res); } } else if (s.equals("inc")) { int x = in.nextInt(); int d = in.nextInt(); out.println(stack.inc(x, d)); } } out.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?"); } }
public static void playerCallCheat() { // declaring variables Scanner in = new Scanner(System.in); String callCheat; int loop = 3; // Loop to keep asking them the question while (loop > 0) { System.out.println("The player played " + lastPlayerNum + " " + localranks[lastPlayerRank]); // getting user input System.out.println("Would you like to call cheat? Y or N"); callCheat = in.next(); // choices if (callCheat.equalsIgnoreCase("y")) { // if the last person cheated if (callCheat(p1hand)) { System.out.println( "Congratulations! You caught the cheater! He gets the pile to his hand."); break; } else { // if the last person didn't cheat System.out.println( "Sorry the last person was not cheating! You get the pile to your hand."); break; } } // if they don't want to call cheat else if (callCheat.equalsIgnoreCase("n")) { break; } // Error handling else { System.out.println("Please enter y or n."); } } }
/** * @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); }
/** 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."); } }
/** 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 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 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; } }
private void readInventoryFromFile() { try { Scanner scan = new Scanner(new File("inventory.txt")); while (scan.hasNext()) { scan.useDelimiter(", "); String id = scan.next().trim(); String title = scan.next().trim(); scan.useDelimiter("\n"); double price = Double.parseDouble(scan.next().replace(",", "").trim()); Book book = new Book(id, title, price); inventory.add(book); } } catch (FileNotFoundException e) { System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n"); } }
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 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(); }