Java Code Examples for java.util.Scanner#next()
The following examples show how to use
java.util.Scanner#next() .
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: BigSorting.java From Hackerrank-Solutions with MIT License | 6 votes |
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[] unsorted = new String[n]; for (int unsorted_i = 0; unsorted_i < n; unsorted_i++) { unsorted[unsorted_i] = in.next(); } Arrays.sort(unsorted, new Comparator<String>() { public int compare(String s1, String s2) { return compareStrings(s1, s2); } }); printArray(unsorted); in.close(); }
Example 2
Source File: TaskServerNode1.java From jeesuite-libs with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException{ final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test-schduler.xml"); InstanceFactory.setInstanceProvider(new SpringInstanceProvider(context)); logger.info("TASK started...."); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { logger.info("TASK Stoped...."); context.close(); } })); Scanner scan=new Scanner(System.in); String cmd=scan.next(); if("q".equals(cmd)){ scan.close(); context.close(); } }
Example 3
Source File: StompMessage.java From StompProtocolAndroid with MIT License | 6 votes |
public static StompMessage from(@Nullable String data) { if (data == null || data.trim().isEmpty()) { return new StompMessage(StompCommand.UNKNOWN, null, data); } Scanner reader = new Scanner(new StringReader(data)); reader.useDelimiter("\\n"); String command = reader.next(); List<StompHeader> headers = new ArrayList<>(); while (reader.hasNext(PATTERN_HEADER)) { Matcher matcher = PATTERN_HEADER.matcher(reader.next()); matcher.find(); headers.add(new StompHeader(matcher.group(1), matcher.group(2))); } reader.skip("\n\n"); reader.useDelimiter(TERMINATE_MESSAGE_SYMBOL); String payload = reader.hasNext() ? reader.next() : null; return new StompMessage(command, headers, payload); }
Example 4
Source File: IncludeExcludeFilter.java From connector-sdk with Apache License 2.0 | 6 votes |
@VisibleForTesting static void mainHelper(String[] args, java.io.InputStream inStream) throws java.io.IOException { Configuration.initConfig(args); IncludeExcludeFilter filter = IncludeExcludeFilter.fromConfiguration(); System.out.println("Rules:"); Stream.concat(filter.prefixIncludeRules.stream(), filter.prefixExcludeRules.stream()) .forEach(rule -> System.out.println("*** " + rule)); Stream.concat( filter.regexIncludeRules.values().stream().filter(list -> !list.isEmpty()), filter.regexExcludeRules.values().stream().filter(list -> !list.isEmpty())) .forEach(list -> list.stream().forEach(rule -> System.out.println("*** " + rule))); System.out.println(); System.out.println("Enter test value(s)"); Scanner in = new Scanner(inStream); while (in.hasNext()) { String value = in.next(); System.out.println(value); for (ItemType itemType : ItemType.values()) { System.out.println(" as " + itemType.name() + ": " + filter.isAllowed(value, itemType)); } System.out.println(); } }
Example 5
Source File: LoadBooks.java From Java-Data-Analysis with MIT License | 6 votes |
public static void load(MongoCollection collection) { try { Scanner fileScanner = new Scanner(DATA); int n = 0; while (fileScanner.hasNext()) { String line = fileScanner.nextLine(); Scanner lineScanner = new Scanner(line).useDelimiter("/"); String title = lineScanner.next(); int edition = lineScanner.nextInt(); String cover = lineScanner.next(); String publisher = lineScanner.next(); int year = lineScanner.nextInt(); String _id = lineScanner.next(); int pages = lineScanner.nextInt(); lineScanner.close(); addDoc(_id, title, edition, publisher, year, cover, pages, collection); System.out.printf("%4d. %s, %s, %s, %d%n", ++n, _id, title, publisher, year); } System.out.printf("%d docs inserted in books collection.%n", n); fileScanner.close(); } catch (IOException e) { System.err.println(e); } }
Example 6
Source File: JavaList.java From Hackerrank-Solutions with MIT License | 6 votes |
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> L = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { L.add(sc.nextInt()); } int Q = sc.nextInt(); for (int i = 0; i < Q; i++) { String op = sc.next(); if (op.equalsIgnoreCase("INSERT")) { int index = sc.nextInt(); int item = sc.nextInt(); L.add(index, item); } else { L.remove(sc.nextInt()); } } for (Integer integer : L) { System.out.print(integer + " "); } sc.close(); }
Example 7
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 8
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 9
Source File: TableCreater.java From ezScrum with GNU General Public License v2.0 | 6 votes |
/************************************************************ * 執行SQL Script *************************************************************/ public static void importSQL(Connection conn, InputStream in) throws SQLException { Scanner s = new Scanner(in,"UTF-8"); s.useDelimiter("(;(\r)?\n)|(--\n)"); Statement st = null; try { st = conn.createStatement(); while (s.hasNext()) { String line = s.next(); if (line.startsWith("/*!") && line.endsWith("*/")) { int i = line.indexOf(' '); line = line.substring(i + 1, line.length() - " */".length()); } if (line.trim().length() > 0) { st.execute(line); } } } finally { if (st != null) st.close(); } }
Example 10
Source File: SolC.java From web3j-maven-plugin with Apache License 2.0 | 6 votes |
private File initBundled() throws IOException { File solC = null; File tmpDir = new File(System.getProperty("java.io.tmpdir"), "solc"); tmpDir.setReadable(true); tmpDir.setWritable(true); tmpDir.setExecutable(true); tmpDir.mkdirs(); String solcPath = "/native/" + getOS() + "/solc/"; InputStream is = getClass().getResourceAsStream(solcPath + "file.list"); Scanner scanner = new Scanner(is); if (scanner.hasNext()) { // first file in the list denotes executable String s = scanner.next(); File targetFile = new File(tmpDir, s); InputStream fis = getClass().getResourceAsStream(solcPath + s); Files.copy(fis, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); solC = targetFile; solC.setExecutable(true); targetFile.deleteOnExit(); } tmpDir.deleteOnExit(); return solC; }
Example 11
Source File: TzdbZoneRulesCompiler.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private int parseMonth(Scanner s) { if (s.hasNext(MONTH)) { s.next(MONTH); for (int moy = 1; moy < 13; moy++) { if (s.match().group(moy) != null) { return moy; } } } throw new IllegalArgumentException("Unknown month: " + s.next()); }
Example 12
Source File: BinaryToHexadecimalConversion.java From Mathematics with MIT License | 5 votes |
/** * Main method * @param args */ public static void main(String[] args) { Scanner myScanner=new Scanner(System.in); String binaryNumber; boolean restartProgram=false; //Prompt user to input a binary number System.out.print("Please input a binary number to convert: "); binaryNumber=myScanner.next(); if (!binaryIsValid(binaryNumber)){ restartProgram=true; } else{ restartProgram=false; String hexNumber = null; if (binaryNumber.length()>4){ ArrayList<String> tempParts=getParts(binaryNumber); StringBuilder tempString=new StringBuilder(); for (int i=tempParts.size()-1;i>=0;i--){ tempString.append(binToHex(tempParts.get(i))); } hexNumber=tempString.toString(); } else{ hexNumber=binToHex(binaryNumber); } System.out.println("Binary number: "+binaryNumber + " is equal to hexadecimal number: "+ hexNumber ); } if (restartProgram){ System.err.println("Please provide a valid binary number. Restart the program and try again!"); main(new String[0]); } }
Example 13
Source File: Loading.java From spring-flow-statemachine with MIT License | 5 votes |
public void run(String... strings) throws Exception { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("\r?\n|\r"); System.out.println("Type CREATE <itemId> in order to create a new item.\n" + "Type MOVE <itemId> <state> in order to move item to a new state.\n" + "Type BLOCK <state> in order to remove state from state machine.\n" + "Available <state> values are: first, second third\n" + "Type EXIT to terminate."); while (true) { String command = scanner.next(); parseCommand(command); } }
Example 14
Source File: MimaTimeClient.java From frameworkAggregate with Apache License 2.0 | 5 votes |
public static void main(String[] args) { IoConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8")))); connector.setHandler(new TimeClientHander()); ConnectFuture connectFuture = connector.connect(new InetSocketAddress("127.0.0.1", PORT)); // 等待建立连接 connectFuture.awaitUninterruptibly(); System.out.println("连接成功"); IoSession session = connectFuture.getSession(); Scanner sc = new Scanner(System.in); boolean quit = false; while (!quit) { String str = sc.next(); if (str.equalsIgnoreCase("quit")) { quit = true; } session.write(str); } // 关闭 if (session != null) { if (session.isConnected()) { session.getCloseFuture().awaitUninterruptibly(); } connector.dispose(true); } }
Example 15
Source File: JavaBigInteger.java From Hackerrank-Solutions with MIT License | 5 votes |
public static void main(String[] args) { Scanner sc = new Scanner(System.in); BigInteger a = new BigInteger(sc.next()); BigInteger b = new BigInteger(sc.next()); System.out.println(a.add(b)); System.out.println(a.multiply(b)); sc.close(); }
Example 16
Source File: Java Regex.java From HackerRank-Solutions with The Unlicense | 5 votes |
public static void main(String []args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } }
Example 17
Source File: PunycodeTest.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public String testEncoding(String inputS) { char input[] = new char[unicode_max_length]; int codept = 0; char uplus[] = new char[2]; StringBuffer output; int c; /* Read the input code points: */ input_length = 0; Scanner sc = new Scanner(inputS); while (sc.hasNext()) { // need to stop at end of line try { String next = sc.next(); uplus[0] = next.charAt(0); uplus[1] = next.charAt(1); codept = Integer.parseInt(next.substring(2), 16); } catch (Exception ex) { fail(invalid_input, inputS); } if (uplus[1] != '+' || codept > Integer.MAX_VALUE) { fail(invalid_input, inputS); } if (input_length == unicode_max_length) fail(too_big, inputS); if (uplus[0] == 'u') case_flags[input_length] = false; else if (uplus[0] == 'U') case_flags[input_length] = true; else fail(invalid_input, inputS); input[input_length++] = (char)codept; } /* Encode: */ output_length[0] = ace_max_length; try { output = Punycode.encode((new StringBuffer()).append(input, 0, input_length), case_flags); } catch (Exception e) { fail(invalid_input, inputS); // never reach here, just to make compiler happy return null; } testCount++; return output.toString(); }
Example 18
Source File: MRLocalClusterIntegrationTest.java From hadoop-mini-clusters with Apache License 2.0 | 4 votes |
private String resourceFileToString(String fileName) { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; }
Example 19
Source File: JavaPriorityQueue.java From Hackerrank-Solutions with MIT License | 4 votes |
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); PriorityQueue<Student> data = new PriorityQueue<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (o1.getCgpa() < o2.getCgpa()) { return 1; } else if (o1.getCgpa() > o2.getCgpa()) { return -1; } else { if (o1.getFname().compareTo(o2.getFname()) == 0) { if (o1.getToken() > o2.getToken()) { return 1; } else if (o1.getToken() < o2.getToken()) { return -1; } else { return 0; } } else { return o1.getFname().compareTo(o2.getFname()); } } } }); for (int i = 0; i < t; i++) { String op = sc.next(); switch (op) { case "ENTER": String name = sc.next(); double cgpa = sc.nextDouble(); int id = sc.nextInt(); Student s = new Student(id, name, cgpa); data.add(s); break; case "SERVED": if (data.isEmpty()) { break; } data.remove(); } } if (data.isEmpty()) System.out.println("EMPTY"); else { while (!data.isEmpty()) { Student st = data.poll(); System.out.println(st.getFname()); } } sc.close(); }
Example 20
Source File: AsyncHttpURLConnection.java From sample-videoRTC with Apache License 2.0 | 4 votes |
private static String drainStream(InputStream in) { Scanner s = new Scanner(in, "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; }