Tabnine Logo
Scanner
Code IndexAdd Tabnine to your IDE (free)

How to use
Scanner
in
java.util

Best Java code snippets using java.util.Scanner (Showing top 20 results out of 15,444)

origin: stackoverflow.com

 static String convertStreamToString(java.io.InputStream is) {
  java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
  return s.hasNext() ? s.next() : "";
}
origin: apache/incubator-dubbo

/**
 * visible width for the given string.
 *
 * for example: "abc\n1234"'s width is 4.
 *
 * @param string the given string
 * @return visible width
 */
private static int width(String string) {
  int maxWidth = 0;
  try (Scanner scanner = new Scanner(new StringReader(string))) {
    while (scanner.hasNextLine()) {
      maxWidth = max(length(scanner.nextLine()), maxWidth);
    }
  }
  return maxWidth;
}
origin: stackoverflow.com

 Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
 String line = scanner.nextLine();
 // process the line
}
scanner.close();
origin: stackoverflow.com

 try (Scanner scanner = new Scanner(response)) {
  String responseBody = scanner.useDelimiter("\\A").next();
  System.out.println(responseBody);
}
origin: stackoverflow.com

 System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
origin: stackoverflow.com

 Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
  System.out.println(
    sc.hasNextInt() ? "(int) " + sc.nextInt() :
    sc.hasNextLong() ? "(long) " + sc.nextLong() :  
    sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
    sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
    "(String) " + sc.next()
  );
}
origin: stackoverflow.com

 public static boolean isInteger(String s, int radix) {
  Scanner sc = new Scanner(s.trim());
  if(!sc.hasNextInt(radix)) return false;
  // we know it starts with a valid int, now make sure
  // there's nothing left!
  sc.nextInt(radix);
  return !sc.hasNext();
}
origin: stackoverflow.com

 Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
  System.out.println("That's not a vowel!");
  sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
origin: stackoverflow.com

 Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
reader.close();
origin: robolectric/robolectric

public JavaVersion(String version) {
 versions = new ArrayList<>();
 Scanner s = new Scanner(version).useDelimiter("[^\\d]+");
 while (s.hasNext()) {
  versions.add(s.nextInt());
 }
}
origin: stackoverflow.com

Scanner scanner = new Scanner(a);
scanner.useDelimiter(",");
scanner.close();
origin: stackoverflow.com

 import java.util.Scanner; 
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
origin: stackoverflow.com

 Scanner sc = new Scanner(System.in);
int number;
do {
  System.out.println("Please enter a positive number!");
  while (!sc.hasNextInt()) {
    System.out.println("That's not a number!");
    sc.next(); // this is important!
  }
  number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
origin: spring-projects/spring-framework

@Override
public Resource transform(HttpServletRequest request, Resource resource,
    ResourceTransformerChain chain) throws IOException {
  resource = chain.transform(request, resource);
  if (!this.fileExtension.equals(StringUtils.getFilenameExtension(resource.getFilename()))) {
    return resource;
  }
  byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
  String content = new String(bytes, DEFAULT_CHARSET);
  if (!content.startsWith(MANIFEST_HEADER)) {
    if (logger.isTraceEnabled()) {
      logger.trace("Skipping " + resource + ": Manifest does not start with 'CACHE MANIFEST'");
    }
    return resource;
  }
  @SuppressWarnings("resource")
  Scanner scanner = new Scanner(content);
  LineInfo previous = null;
  LineAggregator aggregator = new LineAggregator(resource, content);
  while (scanner.hasNext()) {
    String line = scanner.nextLine();
    LineInfo current = new LineInfo(line, previous);
    LineOutput lineOutput = processLine(current, request, resource, chain);
    aggregator.add(lineOutput);
    previous = current;
  }
  return aggregator.createResource();
}
origin: kevin-wayne/algs4

/**
 * Reads and returns the remainder of this input stream, as a string.
 *
 * @return the remainder of this input stream, as a string
 */
public String readAll() {
  if (!scanner.hasNextLine())
    return "";
  String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
  // not that important to reset delimeter, since now scanner is empty
  scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
  return result;
}
origin: stackoverflow.com

 Scanner scanner = null;
try {
  scanner = new Scanner(System.in);
  //rest of the code
}
finally {
  if(scanner!=null)
    scanner.close();
}
origin: stackoverflow.com

 public void readShapeData() throws IOException {
  Scanner in = new Scanner(System.in);
  try {
    System.out.println("Enter the width of the Rectangle: ");
    width = in.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = in.nextDouble();
  } finally {
    in.close();
  }
}
origin: spring-projects/spring-framework

LineInfoGenerator(String content) {
  this.scanner = new Scanner(content);
}
origin: apache/hbase

private static int readPidFromFile(String pidFile) throws IOException {
 Scanner scanner = new Scanner(new File(pidFile));
 try {
  return scanner.nextInt();
 } finally {
  scanner.close();
 }
}
origin: pmd/pmd

private void mapLinesToOffsets() throws IOException {
  try (Scanner scanner = new Scanner(filePath)) {
    int currentGlobalOffset = 0;
    while (scanner.hasNextLine()) {
      lineToOffset.add(currentGlobalOffset);
      currentGlobalOffset += getLineLengthWithLineSeparator(scanner);
    }
  }
}
java.utilScanner

Javadoc

A parser that parses a text string of primitive types and strings with the help of regular expressions. This class is not as useful as it might seem. It's very inefficient for communicating between machines; you should use JSON, protobufs, or even XML for that. Very simple uses might get away with String#split. For input from humans, the use of locale-specific regular expressions make it not only expensive but also somewhat unpredictable.

This class supports localized numbers and various radixes. The input is broken into tokens by the delimiter pattern, which is \\p{javaWhitespace}} by default.

Example:

 
Scanner s = new Scanner("1A true"); 
assertEquals(26, s.nextInt(16)); 
assertEquals(true, s.nextBoolean()); 

The Scanner class is not thread-safe.

Most used methods

  • <init>
  • next
    Returns the next token if it matches the specified pattern. The token will be both prefixed and suff
  • nextLine
    Returns the skipped input and advances the Scanner to the beginning of the next line. The returned r
  • useDelimiter
    Sets the delimiting pattern of this Scanner.
  • hasNext
    Returns whether this Scanner has one or more tokens remaining to parse and the next token matches th
  • close
    Closes this Scanner and the underlying input if the input implements Closeable. If the Scanner has b
  • hasNextLine
    Returns true if there is a line terminator in the input. This method may block.
  • nextInt
    Returns the next token as an int with the specified radix. This method will block if input is being
  • nextDouble
    Returns the next token as a double. This method will block if input is being read. If the next token
  • hasNextInt
    Returns whether the next token can be translated into a valid intvalue in the specified radix.
  • findInLine
    Tries to find the pattern in the input. Delimiters are ignored. If the pattern is found before line
  • nextLong
    Returns the next token as a long with the specified radix. This method will block if input is being
  • findInLine,
  • nextLong,
  • match,
  • nextFloat,
  • findWithinHorizon,
  • useLocale,
  • hasNextDouble,
  • skip,
  • hasNextLong,
  • nextByte

Popular in Java

  • Making http requests using okhttp
  • startActivity (Activity)
  • getSupportFragmentManager (FragmentActivity)
  • findViewById (Activity)
  • FileWriter (java.io)
    A specialized Writer that writes to a file in the file system. All write requests made by calling me
  • PrintWriter (java.io)
    Wraps either an existing OutputStream or an existing Writerand provides convenience methods for prin
  • SocketTimeoutException (java.net)
    This exception is thrown when a timeout expired on a socket read or accept operation.
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • TimeUnit (java.util.concurrent)
    A TimeUnit represents time durations at a given unit of granularity and provides utility methods to
  • ReentrantLock (java.util.concurrent.locks)
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now