java.util.Scanner Java Examples
The following examples show how to use
java.util.Scanner.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModernArt2.java From Algorithms with MIT License | 7 votes |
public static void main(String[] args) throws Exception{ Scanner scan=new Scanner(new File("art2.in")); PrintWriter writer = new PrintWriter(new File("art2.out")); int n=scan.nextInt(); int[] paint=new int[n]; int ans; if(n==7){ ans=2; }else{ ans=6; } writer.println(ans); writer.close(); }
Example #2
Source File: AnagramsQuick.java From algorithms with MIT License | 7 votes |
public List<String> findAnagramsQuickly(String pathToFile, String word) { long startTime = System.nanoTime(); List<String> result = new ArrayList<>(); try { Scanner sc = new Scanner(new File(pathToFile), "Cp1252"); char[] wordChars = word.toLowerCase().toCharArray(); Map<Character, Integer> countMap = new HashMap<>(); for(char character : wordChars) { countMap.put(character,countMap.getOrDefault(character, 0) + 1); } while (sc.hasNextLine()) { String curWord = sc.nextLine(); if (curWord.length() == word.length()) { if (isAnagram(curWord, new HashMap<>(countMap))) { result.add(curWord); } } } } catch (IOException ioException) { throw new RuntimeException(ioException); } System.out.println("Nano seconds taken:" + (System.nanoTime() - startTime)); return result; }
Example #3
Source File: Volume.java From Mathematics with MIT License | 6 votes |
public static void main(String[] args){ System.out.println("________Welcome to Volume Calculation________\n"); System.out.println("Choose one of the following\n"); Scanner scan = new Scanner(System.in); System.out.println("1 Cube \n" + "2 Cuboid \n" + "3 Cylinder\n" + "4 Sphere \n" + "5 Pyramid \n"); int userChoice = scan.nextInt(); switch(userChoice){ case 1: cube(); break; case 2: cuboid(); break; case 3: cylinder(); break; case 4: sphere(); break; case 5: pyramid(); break; default: System.out.println("Invalid Choice! Try Again\n"); } }
Example #4
Source File: NetworkUtils.java From android-dev-challenge with Apache License 2.0 | 6 votes |
/** * This method returns the entire result from the HTTP response. * * @param url The URL to fetch the HTTP response from. * @return The contents of the HTTP response, null if no response * @throws IOException Related to network and stream reading */ public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); String response = null; if (hasInput) { response = scanner.next(); } scanner.close(); return response; } finally { urlConnection.disconnect(); } }
Example #5
Source File: ExecutionUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * This method will return true if user enters Yes and will return false if user enters No or simply presses Enter key i.e. leaves blank answer * * @param reader * @param validMessage * @param question * TODO * @return * @throws JumbuneException */ public static boolean askYesNoInfo(Scanner scanner, String validMessage, String question) { YesNo yesNo; askQuestion(question); while (true) { try { String input; input = readFromReader(scanner); if (input.length() == 0) { return false; } yesNo = YesNo.valueOf(input.toUpperCase()); break; } catch (IllegalArgumentException ilEx) { CONSOLE_LOGGER.error(validMessage); } } if (YesNo.YES.equals(yesNo) || YesNo.Y.equals(yesNo)) { return true; } return false; }
Example #6
Source File: Solution.java From JavaRushTasks with MIT License | 6 votes |
public static void main(String[] args) throws Exception { //напишите тут ваш код int[] vect = new int[15]; Scanner sc = new Scanner(System.in); for (int i=0;i<vect.length;i++) { vect[i] = Integer.parseInt(sc.nextLine()); } int even_sum = 0; int odd_sum = 0; for (int i=0;i<vect.length;i++) { if ((i % 2) ==0) even_sum += vect[i]; else odd_sum += vect[i]; } if (even_sum>odd_sum) System.out.println("В домах с четными номерами проживает больше жителей."); else System.out.println("В домах с нечетными номерами проживает больше жителей."); }
Example #7
Source File: XPreferTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
Dir getChosenOrigin(String compilerOutput) { Scanner s = new Scanner(compilerOutput); while (s.hasNextLine()) { String line = s.nextLine(); if (line.matches("\\[loading .*\\]")) { for (Dir dir : Dir.values()) { // On Windows all paths are printed with '/' except // paths inside zip-files, which are printed with '\'. // For this reason we accept both '/' and '\' below. String regex = dir.file.getName() + "[\\\\/]" + classId; if (Pattern.compile(regex).matcher(line).find()) return dir; } } } return null; }
Example #8
Source File: 10714 Ants.java From UVA with GNU General Public License v3.0 | 6 votes |
public static void main (String [] args) throws Exception { Scanner sc=new Scanner(System.in); int testCaseCount=sc.nextInt(); for (int testCase=0;testCase<testCaseCount;testCase++) { int L=sc.nextInt(); int N=sc.nextInt(); int [] ants=new int[N]; for (int n=0;n<N;n++) ants[n]=sc.nextInt(); Arrays.sort(ants); int shortest=Integer.MIN_VALUE; for (int n=0;n<N;n++) { int left=ants[n]; int right=L-ants[n]; shortest=Math.max(shortest, Math.min(left, right)); } int longest=Math.max(L-ants[0], ants[ants.length-1]); System.out.printf("%d %d\n",shortest,longest); } }
Example #9
Source File: PeerManager.java From jelectrum with MIT License | 6 votes |
private void addSelfToPeer(PrintStream out, Scanner scan) throws org.json.JSONException { JSONArray peersToAdd = new JSONArray(); peersToAdd.put(getServerFeatures()); JSONObject request = new JSONObject(); request.put("id","add_peer"); request.put("method", "server.add_peer"); request.put("params", peersToAdd); out.println(request.toString(0)); out.flush(); //JSONObject reply = new JSONObject(scan.nextLine()); //jelly.getEventLog().log(reply.toString()); }
Example #10
Source File: Stripies_1161.java From AlgoCS with MIT License | 6 votes |
public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Byte n = in.nextByte(); double ans = 0; double a[] = new double[n]; for (int i = 0; i < a.length; i++) { a[i] = in.nextInt(); } Arrays.sort(a); ans = a[a.length - 1]; for (int i = a.length - 1; i > 0; i--) { ans = Max(ans, a[i - 1]); } System.out.printf("%.2f", ans); }
Example #11
Source File: Example1.java From Java-Data-Analysis with MIT License | 6 votes |
public static void map(String filename, PrintWriter writer) throws IOException { Scanner input = new Scanner(new File(filename)); input.useDelimiter("[.,:;()?!\"\\s]+"); while (input.hasNext()) { String word = input.next(); writer.printf("%s 1%n", word.toLowerCase()); } input.close(); }
Example #12
Source File: AndroidComponentScanner.java From mini2Dx with Apache License 2.0 | 6 votes |
@Override public void restoreFrom(Reader reader) throws ClassNotFoundException { final Scanner scanner = new Scanner(reader); boolean singletons = true; scanner.nextLine(); while (scanner.hasNext()) { final String line = scanner.nextLine(); if(line.startsWith("---")) { singletons = false; } else if(singletons) { singletonClasses.add(Class.forName(line)); } else { prototypeClasses.add(Class.forName(line)); } } scanner.close(); }
Example #13
Source File: DepartmentManager.java From ctsms with GNU Lesser General Public License v2.1 | 6 votes |
public void interactiveCreateDepartment() { Scanner in = ExecUtil.getScanner(); try { printDepartments(); System.out.print("enter new department name l10n key:"); String nameL10nKey = in.nextLine(); printDepartmentPasswordPolicy(); String plainDepartmentPassword = readConfirmedPassword(in, "enter department password:", "confirm department password:"); PasswordPolicy.DEPARTMENT.checkStrength(plainDepartmentPassword); createDepartment(nameL10nKey, DEFAULT_DEPARTMENT_VISIBLE, plainDepartmentPassword); System.out.println("department created"); } catch (Exception e) { e.printStackTrace(); } finally { in.close(); } }
Example #14
Source File: Exercise_25_03.java From Intro-to-Java-Programming with MIT License | 6 votes |
public static void main(String[] args) { Scanner input = new Scanner(System.in); Integer[] numbers = new Integer[10]; // Prompt the user to enter 10 integers System.out.print("Enter 10 integers: "); for (int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt(); // Create Integer BST BST<Integer> intTree = new BST<>(numbers); // Traverse tree inorder System.out.print("Tree inorder: "); intTree.inorder(); System.out.println(); }
Example #15
Source File: TextClient.java From StockSimulator with GNU General Public License v2.0 | 6 votes |
public void start() { Scanner scanner = new Scanner(System.in); String nextLine = ""; do { System.out.print("Enter a command (help): "); try { nextLine = scanner.nextLine(); } catch (NoSuchElementException e) { System.out.println("Goodbye"); return; } for (ITextClientSection section:sectionList) { if (section.getName().equalsIgnoreCase(nextLine)){ System.out.println("\n---- Invoking " + section.getName() + " ----"); section.invoke(nextLine, scanner); System.out.println(); } } } while (!nextLine.equalsIgnoreCase("quit")); }
Example #16
Source File: ProbeIB.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(args[0])); try { while (s.hasNextLine()) { String link = s.nextLine(); NetworkInterface ni = NetworkInterface.getByName(link); if (ni != null) { Enumeration<InetAddress> addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); System.out.println(addr.getHostAddress()); } } } } finally { s.close(); } }
Example #17
Source File: TzdbZoneRulesCompiler.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
/** * Parses a Rule line. * * @param s the line scanner, not null */ private void parseRuleLine(Scanner s) { TZDBRule rule = new TZDBRule(); String name = s.next(); if (rules.containsKey(name) == false) { rules.put(name, new ArrayList<TZDBRule>()); } rules.get(name).add(rule); rule.startYear = parseYear(s, 0); rule.endYear = parseYear(s, rule.startYear); if (rule.startYear > rule.endYear) { throw new IllegalArgumentException("Year order invalid: " + rule.startYear + " > " + rule.endYear); } parseOptional(s.next()); // type is unused parseMonthDayTime(s, rule); rule.savingsAmount = parsePeriod(s.next()); rule.text = parseOptional(s.next()); }
Example #18
Source File: DataParserDWI.java From Beats with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static void parseStop(DataFile df, String buffer) throws DataParserException { Scanner vsc = new Scanner(buffer); vsc.useDelimiter(","); while (vsc.hasNext()) { String pair = vsc.next().trim(); try { if (pair.indexOf('=') < 0) { throw new Exception("No '=' found"); } else { float beat = Float.parseFloat(pair.substring(0, pair.indexOf('='))) / 4f; float value = Float.parseFloat(pair.substring(pair.indexOf('=') + 1)) / 1000f; df.addStop(beat, value); } } catch (Exception e) { // Also catch NumberFormatExceptions vsc.close(); throw new DataParserException( e.getClass().getSimpleName(), "Improperly formatted #FREEZE pair \"" + pair + "\": " + e.getMessage(), e ); } } vsc.close(); }
Example #19
Source File: DataHandler.java From OrigamiSMTP with MIT License | 6 votes |
/** Processes the data message * @param inFromClient The input stream from the client */ public void processMessage(Scanner inFromClient) { inFromClient.useDelimiter(""+Constants.CRLF+"."+Constants.CRLF); if(inFromClient.hasNext()) { data = inFromClient.next(); // Clear out buffer inFromClient.nextLine(); inFromClient.nextLine(); response = "250 OK" + Constants.CRLF; } else { response = "501 Syntax Error no lines" + Constants.CRLF; } }
Example #20
Source File: Exercise_03_23.java From Intro-to-Java-Programming with MIT License | 6 votes |
public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a point (x, y) System.out.print("Enter a point with two coordinates: "); double x = input.nextDouble(); double y = input.nextDouble(); // Check whether the point is within the rectangle // centered at (0, 0) with width 10 and height 5 boolean withinRectangle = (Math.pow(Math.pow(x, 2), 0.5) <= 10 / 2 ) || (Math.pow(Math.pow(y, 2), 0.5) <= 5.0 / 2); // Display results System.out.println("Point (" + x + ", " + y + ") is " + ((withinRectangle) ? "in " : "not in ") + "the rectangle"); }
Example #21
Source File: SampleSteamGuardRememberMe.java From JavaSteam with MIT License | 6 votes |
private void onConnected(ConnectedCallback callback) { System.out.println("Connected to Steam! Logging in " + user + "..."); LogOnDetails details = new LogOnDetails(); details.setUsername(user); File loginKeyFile = new File("loginkey.txt"); if (loginKeyFile.exists()) { try (Scanner s = new Scanner(loginKeyFile)) { details.setLoginKey(s.nextLine()); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { details.setPassword(pass); } details.setTwoFactorCode(twoFactorAuth); details.setAuthCode(authCode); details.setShouldRememberPassword(true); steamUser.logOn(details); }
Example #22
Source File: ObservationReader.java From HMMRATAC with GNU General Public License v3.0 | 6 votes |
private List<?> readVector(Scanner inFile){ List<ObservationVector> obseq = new ArrayList<ObservationVector>(); while(inFile.hasNext()){ String line = inFile.nextLine(); String[] temp = line.split(","); double[] values = new double[temp.length]; if (!line.contains("mask")){ for (int i = 0; i < temp.length;i++){ values[i] = Double.parseDouble(temp[i]); } } ObservationVector o = new ObservationVector(values); obseq.add(o); } return obseq; }
Example #23
Source File: Twist1.java From JavaMainRepo with Apache License 2.0 | 6 votes |
public static void main (String[] args){ int i,s=0,nr; String nr1; Scanner in = new Scanner (System.in); nr1 = in.nextLine(); in.close(); try{ nr= Integer.parseInt(nr1); System.out.println("The limit number is " + nr); for(i=2;i<nr;i++){ if((i%3==0) || (i%5==0)) s=s+i; } } catch(NumberFormatException nx){ System.out.println("Enter valid number "); } System.out.println("Sum is " + s); }
Example #24
Source File: RunAlgorithm.java From tutorials with MIT License | 6 votes |
public static void main(String[] args) throws InstantiationException, IllegalAccessException { Scanner in = new Scanner(System.in); System.out.println("Run algorithm:"); System.out.println("1 - Simulated Annealing"); System.out.println("2 - Simple Genetic Algorithm"); System.out.println("3 - Ant Colony"); int decision = in.nextInt(); switch (decision) { case 1: System.out.println( "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); break; case 2: SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); break; case 3: AntColonyOptimization antColony = new AntColonyOptimization(21); antColony.startAntOptimization(); break; default: System.out.println("Unknown option"); break; } in.close(); }
Example #25
Source File: heap_sort.java From Hacktoberfest-Data-Structure-and-Algorithms with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) { Scanner scan = new Scanner( System.in ); System.out.println("Heap Sort Test\n"); int n, i; /* Accept number of elements */ System.out.println("Enter number of integer elements"); n = scan.nextInt(); /* Make array of n elements */ int arr[] = new int[ n ]; /* Accept elements */ System.out.println("\nEnter "+ n +" integer elements"); for (i = 0; i < n; i++) arr[i] = scan.nextInt(); /* Call method sort */ sort(arr); /* Print sorted Array */ System.out.println("\nElements after sorting "); for (i = 0; i < n; i++) System.out.print(arr[i]+" "); System.out.println(); }
Example #26
Source File: BigDecimal.java From Algorithms-and-Data-Structures-in-Java with GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) { //Input Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] s = new String[n + 2]; for (int i = 0; i < n; i++) { s[i] = sc.next(); } sc.close(); //Write your code here s = Arrays.copyOfRange(s, 0, s.length - 2); List<String> input = Arrays.asList(s); Arrays.sort(s, (s1, s2) -> { int compare = new java.math.BigDecimal(s2).compareTo(new java.math.BigDecimal(s1)); if (compare == 0) { return Integer.compare(input.indexOf(s1), input.indexOf(s2)); } return compare; }); //Output for (int i = 0; i < n; i++) { System.out.println(s[i]); } }
Example #27
Source File: ConvertInputStreamToStringBigBenchmark.java From java_in_examples with Apache License 2.0 | 5 votes |
@Benchmark public String jdkScanner() throws IOException { mark(); Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; reset(); return result; }
Example #28
Source File: Main5.java From cs-summary-reflection with Apache License 2.0 | 5 votes |
/** * 例如"abcde"的子序列有"abe","","abcde"等。 定义LCS(S,T)为字符串S和字符串T最长公共子序列的长度,即一个最长的序列W既是S的子序列也是T的子序列的长度。 * 小易给出一个合法的括号匹配序列s,小易希望你能找出具有以下特征的括号序列t: 1、t跟s不同,但是长度相同 2、t也是一个合法的括号匹配序列 3、LCS(s, * t)是满足上述两个条件的t中最大的 因为这样的t可能存在多个,小易需要你计算出满足条件的t有多少个。 如样例所示: s ="(())()",跟字符串s长度相同的合法括号匹配序列有: * "()(())", "((()))", "()()()", "(()())",其中LCS( "(())()", "()(())" )为4,其他三个都为5,所以输出3. */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); char[] c = s.toCharArray(); int len = c.length; // HashMap<String, Integer> map = new HashMap<String Integer>(); HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < len; i++) { // 留空 String s1 = s.substring(0, i); // 每次循环截取字符串中的一个字符出来 String s2 = s.substring(i + 1, len); String s3 = s1 + s2; // 插入 for (int j = 0; j < len; j++) { String b1 = s3.substring(0, j); String b2 = s3.substring(j, len - 1); String e = String.valueOf(c[i]); String b3 = b1 + e + b2; // 将截取出来的字符依次在剩余字符串中插空 if (b3.equals(s)) continue; else { // 匹配 if (istrue(b3)) map.put(b3, 1); } } } System.out.println(map.size()); // System.out.println(istrue("(())()")); sc.close(); }
Example #29
Source File: CleanerTest.java From textidote with GNU General Public License v3.0 | 5 votes |
@Test public void testRemoveAccents1() throws TextCleanerException { LatexCleaner detexer = new LatexCleaner(); detexer.setIgnoreBeforeDocument(false); AnnotatedString as = detexer.clean(AnnotatedString.read(new Scanner("Blabla"))); assertEquals("Blabla", as.toString()); }
Example #30
Source File: GetLandingPageTemplateByName.java From REST-Sample-Code with MIT License | 5 votes |
private String convertStreamToString(InputStream inputStream) { try { return new Scanner(inputStream).useDelimiter("\\A").next(); } catch (NoSuchElementException e) { return ""; } }