List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:com.wandrell.example.swss.client.console.ConsoleClient.java
/** * Returns an integer value read from the input. * <p>/*from w w w . j av a2s.co m*/ * This will try to parse an integer until one is found, rejecting all the * invalid lines. * * @param scanner * scanner for the input * @return an integer read from the input */ private static final Integer getInteger(final Scanner scanner) { Integer integer; // Parsed integer Boolean valid; // Status flag for the loop valid = false; integer = null; while (!valid) { // Runs until an integer is found valid = scanner.hasNextInt(); if (valid) { // Found an integer integer = scanner.nextInt(); } else { // The line is not an integer // It is rejected scanner.nextLine(); } } return integer; }
From source file:com.cisco.dbds.utils.tims.TIMS.java
/** * Readhtmlfile fail.// w ww . j a v a 2s .co m * * @return the array list * @throws FileNotFoundException the file not found exception */ public static ArrayList<String> readhtmlfileFail() throws FileNotFoundException { ArrayList<String> re = new ArrayList<String>(); String fEncoding = "UTF-8"; String tt = ""; int cc = 0; Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding); try { while (scanner.hasNextLine()) { tt = scanner.nextLine(); tt = tt.trim(); if (tt.contains("FAILED TIMS TEST CASES")) { cc = 1; } if (tt.contains("FAILED NON-TIMS TEST CASE ERROR LIST")) { return re; } if (cc == 1 && tt.contains("Ttv") && !(tt.contains("Precheck")) && !(tt.contains("Precondition"))) { int charCount = 0; int pos = 0; if (!tt.startsWith("Ttv")) { for (int i = 0; i < tt.length(); i++) { if (tt.charAt(i) == '_') { charCount++; if (charCount == 2) { pos = i; break; } } } } String tcid = null; if (charCount == 2 && (!tt.startsWith("Ttv"))) { int k = nthOccurrence(tt, '_', 0); tcid = tt.substring(k + 1, tt.length() - 5); if (!tcid.startsWith("Ttv")) { tcid = tt.substring(16, tt.length() - 5); } } else if (charCount == 2) { tcid = tt.substring(pos - 11, tt.length() - 5); } else { tcid = tt.substring(pos + 16, tt.length() - 5); } //System.out.println(tt); System.out.println(tcid); re.add(tcid); } } } finally { scanner.close(); } return re; }
From source file:hyperheuristics.main.comparisons.CompareHypervolumes.java
private static void hypervolumeComparison(String[] problems, String[] heuristicFunctions, int numberOfObjectives) throws InterruptedException, IOException { for (String heuristicFunction : heuristicFunctions) { String path = outpath;// www . j av a2 s. co m String outputDirectory = path + numberOfObjectives + "objectives/" + heuristicFunction + "/"; try (FileWriter fileWriter = new FileWriter(outputDirectory + "HYPERVOLUMES.txt")) { int hyperheuristicBest = 0; int mecbaBest = 0; int tied = 0; int hyperheuristicBestMean = 0; int mecbaBestMean = 0; int tiedMean = 0; int equivalent = 0; for (String problem : problems) { fileWriter.append("Hypervolume comparison for " + problem + ":\n"); fileWriter.append("\n"); HypervolumeHandler hypervolumeHandler = new HypervolumeHandler(); String hyperheuristicDirectory = outputDirectory + problem + "/"; String mecbaDirectory = "resultado/nsgaii/" + problem + "_Comb_" + numberOfObjectives + "obj/"; //Best hypervolume for PFknown hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "FUN.txt"); hypervolumeHandler.addParetoFront(mecbaDirectory + "All_FUN_nsgaii-" + problem); double mecbaHypervolume = hypervolumeHandler .calculateHypervolume(mecbaDirectory + "All_FUN_nsgaii-" + problem, numberOfObjectives); double hyperheuristicHypervolume = hypervolumeHandler .calculateHypervolume(hyperheuristicDirectory + "FUN.txt", numberOfObjectives); fileWriter.append("MECBA PFknown: " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best PFknown: Tied!\n"); tied++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best PFknown: MECBA\n"); mecbaBest++; } else { fileWriter.append("Best PFknown: " + heuristicFunction + "\n"); hyperheuristicBest++; } } //Best mean hypervolume fileWriter.append("\n"); hypervolumeHandler.clear(); for (int i = 0; i < EXECUTIONS; i++) { hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt"); hypervolumeHandler.addParetoFront( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas"); } double[] mecbaHypervolumes = new double[EXECUTIONS]; double[] hyperheuristicHypervolumes = new double[EXECUTIONS]; mecbaHypervolume = 0; hyperheuristicHypervolume = 0; for (int i = 0; i < EXECUTIONS; i++) { mecbaHypervolumes[i] = hypervolumeHandler.calculateHypervolume( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas", numberOfObjectives); mecbaHypervolume += mecbaHypervolumes[i]; hyperheuristicHypervolumes[i] = hypervolumeHandler.calculateHypervolume( hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt", numberOfObjectives); hyperheuristicHypervolume += hyperheuristicHypervolumes[i]; } mecbaHypervolume /= (double) EXECUTIONS; hyperheuristicHypervolume /= (double) EXECUTIONS; fileWriter.append("MECBA (Mean): " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best (Mean): Tied!\n"); tiedMean++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best (Mean): MECBA\n"); mecbaBestMean++; } else { fileWriter.append("Best (Mean): " + heuristicFunction + "\n"); hyperheuristicBestMean++; } String script = ""; script += "MECBA <- c("; for (double value : mecbaHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "MECBA_Hyp <- c("; for (double value : hyperheuristicHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "require(pgirmess)\n"; script += "AR1 <- cbind(MECBA, MECBA_Hyp)\n"; script += "result <- friedman.test(AR1)\n"; script += "m <- data.frame(result$statistic,result$p.value)\n"; script += "pos_teste <- friedmanmc(AR1)\n"; script += "print(pos_teste)"; try (FileWriter scriptWriter = new FileWriter(hyperheuristicDirectory + "temp_input.txt")) { scriptWriter.append(script); } ProcessBuilder processBuilder = new ProcessBuilder("R", "--no-save"); File tempOutput = new File(hyperheuristicDirectory + "temp_output.txt"); processBuilder.redirectOutput(tempOutput); File tempInput = new File(hyperheuristicDirectory + "temp_input.txt"); processBuilder.redirectInput(tempInput); Process process = processBuilder.start(); process.waitFor(); Scanner scanner = new Scanner(tempOutput); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("FALSE")) { equivalent++; fileWriter.append("Statistical Equivalents (Friedman 5%)\n"); break; } } tempInput.delete(); tempOutput.delete(); } fileWriter.append("\n"); fileWriter.append("----------\n"); fileWriter.append("\n"); } fileWriter.append("Problems: " + problems.length + "\n"); fileWriter.append("\n"); fileWriter.append("Tied PFknown: " + tied + "\n"); fileWriter.append("MECBA PFknown: " + mecbaBest + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicBest + "\n"); fileWriter.append("\n"); fileWriter.append("Tied (Mean): " + tiedMean + "\n"); fileWriter.append("MECBA (Mean): " + mecbaBestMean + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicBestMean + "\n"); fileWriter.append("Statistically Equivalent: " + equivalent + "\n"); } } }
From source file:com.sat.spvgt.utils.tims.TIMS.java
/** * Readhtmlfile fail./*w w w. j a va 2 s .c om*/ * * @return the array list * @throws FileNotFoundException * the file not found exception */ public static ArrayList<String> readhtmlfileFail() throws FileNotFoundException { ArrayList<String> re = new ArrayList<String>(); String fEncoding = "UTF-8"; String tt = ""; int cc = 0; Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding); try { while (scanner.hasNextLine()) { tt = scanner.nextLine(); tt = tt.trim(); if (tt.contains("FAILED TIMS TEST CASES")) { cc = 1; } if (tt.contains("FAILED NON-TIMS TEST CASE ERROR LIST")) { return re; } if (cc == 1 && tt.contains("Ttv") && !(tt.contains("Precheck")) && !(tt.contains("Precondition"))) { int charCount = 0; int pos = 0; if (!tt.startsWith("Ttv")) { for (int i = 0; i < tt.length(); i++) { if (tt.charAt(i) == '_') { charCount++; if (charCount == 2) { pos = i; break; } } } } String tcid = null; if (charCount == 2 && (!tt.startsWith("Ttv"))) { int k = nthOccurrence(tt, '_', 0); tcid = tt.substring(k + 1, tt.length() - 5); if (!tcid.startsWith("Ttv")) { tcid = tt.substring(16, tt.length() - 5); } } else if (charCount == 2) { tcid = tt.substring(pos - 11, tt.length() - 5); } else { tcid = tt.substring(pos + 16, tt.length() - 5); } // System.out.println(tt); System.out.println(tcid); re.add(tcid); } } } finally { scanner.close(); } return re; }
From source file:eu.cassandra.utils.Utils.java
/** * This function is used when the user has already tracked the electrical * appliances installed in the installation. He can used them as a base case * and extend it with any additional ones that may be found during the later * stages of analysis of the consumption. * /*w w w . j a va 2 s .co m*/ * @param filename * The filename of the file containing the appliances. * @return * A list of appliances * @throws FileNotFoundException */ public static ArrayList<Appliance> appliancesFromFile(String filename) throws FileNotFoundException { // Read appliance file and start appliance parsing File file = new File(filename); Scanner input = new Scanner(file); ArrayList<Appliance> appliances = new ArrayList<Appliance>(); String nextLine; String[] line; while (input.hasNextLine()) { nextLine = input.nextLine(); line = nextLine.split(","); String name = line[0]; String activity = line[1]; if (activity.contains("Standby") == false && activity.contains("Refrigeration") == false) { double p = Double.parseDouble(line[2]); double q = Double.parseDouble(line[3]); // For each appliance found in the file, an temporary Appliance // Entity is created. appliances.add(new Appliance(name, activity, p, q, 0, 100)); } } System.out.println("Appliances:" + appliances.size()); input.close(); return appliances; }
From source file:com.joliciel.talismane.stats.FScoreCalculator.java
/** * Combine the results of n cross validation results into a single f-score file. * @param directory/*from w ww. j av a 2 s .c om*/ * @param prefix * @param suffix * @param csvFileWriter */ static void combineCrossValidationResults(File directory, String prefix, String suffix, Writer csvFileWriter) { try { File[] files = directory.listFiles(); Map<Integer, Map<String, FScoreStats>> fileStatsMap = new HashMap<Integer, Map<String, FScoreStats>>(); for (File file : files) { if (file.getName().startsWith(prefix) && file.getName().endsWith(suffix)) { int index = Integer.parseInt(file.getName().substring(prefix.length(), prefix.length() + 1)); Map<String, FScoreStats> statsMap = new HashMap<String, FScoreCalculator.FScoreStats>(); fileStatsMap.put(index, statsMap); Scanner scanner = new Scanner( new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))); boolean firstLine = true; int truePositivePos = -1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); List<String> cells = CSV.getCSVCells(line); if (firstLine) { int i = 0; for (String cell : cells) { if (cell.equals("true+")) { truePositivePos = i; break; } i++; } if (truePositivePos < 0) { throw new JolicielException("Couldn't find true+ on first line"); } firstLine = false; } else { FScoreStats stats = new FScoreStats(); String outcome = cells.get(0); stats.outcome = outcome; if (outcome.equals("AVERAGE")) break; stats.truePos = Integer.parseInt(cells.get(truePositivePos)); stats.falsePos = Integer.parseInt(cells.get(truePositivePos + 1)); stats.falseNeg = Integer.parseInt(cells.get(truePositivePos + 2)); stats.precision = Double.parseDouble(cells.get(truePositivePos + 3)); stats.recall = Double.parseDouble(cells.get(truePositivePos + 4)); stats.fScore = Double.parseDouble(cells.get(truePositivePos + 5)); statsMap.put(outcome, stats); } // firstLine? } // has more lines scanner.close(); } // file in current series } // next file int numFiles = fileStatsMap.size(); if (numFiles == 0) { throw new JolicielException("No files found matching prefix and suffix provided"); } Map<String, DescriptiveStatistics> descriptiveStatsMap = new HashMap<String, DescriptiveStatistics>(); Map<String, FScoreStats> outcomeStats = new HashMap<String, FScoreCalculator.FScoreStats>(); Set<String> outcomes = new TreeSet<String>(); for (Map<String, FScoreStats> statsMap : fileStatsMap.values()) { for (FScoreStats stats : statsMap.values()) { DescriptiveStatistics fScoreStats = descriptiveStatsMap.get(stats.outcome + "fScore"); if (fScoreStats == null) { fScoreStats = new DescriptiveStatistics(); descriptiveStatsMap.put(stats.outcome + "fScore", fScoreStats); } fScoreStats.addValue(stats.fScore); DescriptiveStatistics precisionStats = descriptiveStatsMap.get(stats.outcome + "precision"); if (precisionStats == null) { precisionStats = new DescriptiveStatistics(); descriptiveStatsMap.put(stats.outcome + "precision", precisionStats); } precisionStats.addValue(stats.precision); DescriptiveStatistics recallStats = descriptiveStatsMap.get(stats.outcome + "recall"); if (recallStats == null) { recallStats = new DescriptiveStatistics(); descriptiveStatsMap.put(stats.outcome + "recall", recallStats); } recallStats.addValue(stats.recall); FScoreStats outcomeStat = outcomeStats.get(stats.outcome); if (outcomeStat == null) { outcomeStat = new FScoreStats(); outcomeStat.outcome = stats.outcome; outcomeStats.put(stats.outcome, outcomeStat); } outcomeStat.truePos += stats.truePos; outcomeStat.falsePos += stats.falsePos; outcomeStat.falseNeg += stats.falseNeg; outcomes.add(stats.outcome); } } csvFileWriter.write(CSV.format(prefix + suffix)); csvFileWriter.write("\n"); csvFileWriter.write(CSV.format("outcome")); csvFileWriter.write(CSV.format("true+") + CSV.format("false+") + CSV.format("false-") + CSV.format("tot precision") + CSV.format("avg precision") + CSV.format("dev precision") + CSV.format("tot recall") + CSV.format("avg recall") + CSV.format("dev recall") + CSV.format("tot f-score") + CSV.format("avg f-score") + CSV.format("dev f-score") + "\n"); for (String outcome : outcomes) { csvFileWriter.write(CSV.format(outcome)); FScoreStats outcomeStat = outcomeStats.get(outcome); DescriptiveStatistics fScoreStats = descriptiveStatsMap.get(outcome + "fScore"); DescriptiveStatistics precisionStats = descriptiveStatsMap.get(outcome + "precision"); DescriptiveStatistics recallStats = descriptiveStatsMap.get(outcome + "recall"); outcomeStat.calculate(); csvFileWriter.write(CSV.format(outcomeStat.truePos)); csvFileWriter.write(CSV.format(outcomeStat.falsePos)); csvFileWriter.write(CSV.format(outcomeStat.falseNeg)); csvFileWriter.write(CSV.format(outcomeStat.precision * 100)); csvFileWriter.write(CSV.format(precisionStats.getMean())); csvFileWriter.write(CSV.format(precisionStats.getStandardDeviation())); csvFileWriter.write(CSV.format(outcomeStat.recall * 100)); csvFileWriter.write(CSV.format(recallStats.getMean())); csvFileWriter.write(CSV.format(recallStats.getStandardDeviation())); csvFileWriter.write(CSV.format(outcomeStat.fScore * 100)); csvFileWriter.write(CSV.format(fScoreStats.getMean())); csvFileWriter.write(CSV.format(fScoreStats.getStandardDeviation())); csvFileWriter.write("\n"); csvFileWriter.flush(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:hu.petabyte.redflags.PassEncoder.java
@Test public void test() { BCryptPasswordEncoder e = new BCryptPasswordEncoder(); Scanner s = new Scanner(System.in); String i;// w w w .j a v a 2 s. co m while (!(i = s.nextLine()).isEmpty()) { System.out.println("ENC: " + e.encode(i)); } s.close(); }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Get connections synchronously. /*from ww w. ja v a 2 s. co m*/ * Operation blocks until it is completed. * * @param tgServer TG server to get connections from * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one * @param logFile TG admin log file location - Generated by admin * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever * @return Array of session IDs * @throws TGAdminException Admin execution fails or timeout occurs */ public static String[] getConnections(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel, long timeout) throws TGAdminException { String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout); Scanner scanner = new Scanner(output); boolean counting = false; //int indexClientId; int indexSessionId = 0; int adminConnectionCount = 0; List<String> connectionList = new ArrayList<String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("Client ID")) { counting = true; //indexClientId = line.indexOf("Client ID"); indexSessionId = line.indexOf("Session ID"); } else if (line.contains("----------")) counting = false; else if (line.contains("connection(s) returned")) { counting = false; adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0))); } else if (counting) { connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId))); } } scanner.close(); if (connectionList.size() != adminConnectionCount) throw new TGAdminException("TGAdmin - Not able to determine number of connections"); return connectionList.toArray(new String[0]); }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Get connections for a given user. //from www . j a v a 2s . c o m * Operation blocks until it is completed. * * @param tgServer TG server to get connections from * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one * @param user User name to get the connections from * @param logFile TG admin log file location - Generated by admin * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever * * @return Array of session IDs belonging to the user * @throws TGAdminException Admin execution fails or timeout occurs */ public static String[] getConnectionsByUser(TGServer tgServer, String tgNetListenerName, String user, String logFile, String logLevel, long timeout) throws TGAdminException { String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout); Scanner scanner = new Scanner(output); boolean counting = false; //int indexClientId; int indexSessionId = 0; //int adminConnectionCount = 0; List<String> connectionList = new ArrayList<String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("Client ID")) { counting = true; //indexClientId = line.indexOf("Client ID"); indexSessionId = line.indexOf("Session ID"); } else if (line.contains("----------")) counting = false; else if (line.contains("connection(s) returned")) { counting = false; //adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0))); } else if (counting) { if (line.contains(" " + user + " ")) connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId))); } } scanner.close(); //if (connectionList.size() != adminConnectionCount) // throw new TGAdminException("TGAdmin - Not able to determine number of connections"); return connectionList.toArray(new String[0]); }
From source file:mini_mirc_client.Mini_mirc_client.java
private static void perform(TTransport transport, miniIRC.Client client) throws TException { //private static void perform () throws TException { boolean exit = false; Scanner input = new Scanner(System.in); generateUname();//from ww w .j a va 2s .co m //auto-regis int res; synchronized (transport) { transport.open(); res = client.regUser(username); transport.close(); if (res == 0) { System.out.println("# Registered user: " + username); } else { System.out.println("!!!: Unidentified error on register!"); generateUname(); transport.open(); res = client.regUser(username); if (res == 0) System.out.println("# Registered user: " + username); transport.close(); } } while (!exit) { System.out.print("> "); String command = input.nextLine(); String resSplit[] = command.split(" ", 2); String commandWord = resSplit[0].toUpperCase(); synchronized (transport) { transport.open(); switch (commandWord) { case "/NICK": System.out.println("# Registering user: " + resSplit[1]); res = client.regUser(resSplit[1]); if (res == 0) { System.out.println("# Registered user: " + resSplit[1]); username = resSplit[1]; } else if (res == 2) { System.out.println("# Login as user: " + resSplit[1]); username = resSplit[1]; } else { System.out.println("!!!: Unidentified error on register!"); } break; case "/JOIN": System.out.println("# Checking channel: " + resSplit[1]); res = client.join(username, resSplit[1]); if (res == 0 || res == 2) { System.out.println("# Joined channel: " + resSplit[1]); } else { if (res == 1) { System.out.println("!!!: Channel " + resSplit[1] + " already joined!"); } else { System.out.println("!!!: code #" + res + " on channel join"); } } break; case "/LEAVE": if (username.isEmpty()) { System.out.println("!!!: Unregistered user"); } else { System.out.println("# " + username + " exiting channel " + resSplit[1]); res = client.leave(username, resSplit[1]); if (res == 0) System.out.println("# Success"); else System.out.println("!!!: Channel error!"); } break; case "/EXIT": System.out.println("# " + username + " closing..."); res = client.exit(username); if (res == 0) { System.out.println("# Exit success"); username = ""; exit = true; update = false; } else { System.out.println("!!!: Channel error! Error code #" + res); } break; default: if (resSplit[0].startsWith("@")) { // message to channel res = client.message(username, resSplit[0].substring(1), resSplit[1]); if (res == 0) { System.out.println("# Msg to " + resSplit[0].substring(1) + " sent"); } else if (res == 2) { System.out.println("!!!: Not member of channel " + resSplit[0].substring(1)); } } else { res = client.message(username, "*", command); if (res == 0) { System.out.println("# Msg to all channels sent"); } else { System.out.println("!!!: Connection problemo?"); } } break; } transport.close(); } showMsg(); } }