Java Code Examples for java.util.Scanner#hasNext()

The following examples show how to use java.util.Scanner#hasNext() . 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: Properties.java    From CircuitSim with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int[] parsePartial(String contents) {
	int[] values = new int[1 << addressBits];
	
	Scanner scanner = new Scanner(contents);
	int length;
	for(length = 0; length < values.length && scanner.hasNext(); length++) {
		String piece = scanner.next();
		if(piece.matches("^\\d+-[\\da-fA-F]+$")) {
			String[] split = piece.split("-");
			int count = Integer.parseInt(split[0]);
			int val = parseValue(split[1]);
			for(int j = 0; j < count && length < values.length; j++, length++) {
				values[length] = val;
			}
			length--; // to account for extra increment
		} else {
			values[length] = parseValue(piece);
		}
	}
	return Arrays.copyOf(values, length);
}
 
Example 2
Source File: Filter1.java    From Java-Data-Analysis with MIT License 6 votes vote down vote up
public static int[][] computeUtilityMatrix(File file) 
        throws FileNotFoundException {
    Scanner in = new Scanner(file);
    //  Read the five header lines:
    m = in.nextInt();  in.nextLine();
    n = in.nextInt();  in.nextLine();
    in.nextLine();  in.nextLine();  in.nextLine();

    //  Read in the utility matrix:
    int[][] u = new int[m+1][n+1];
    while (in.hasNext()) {
        int i = in.nextInt();  // user
        int j = in.nextInt();  // item
        u[i][j] = 1;
    }
    in.close();
    return u;
}
 
Example 3
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 * @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();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 4
Source File: NumberUtils.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if a string is a valid integer in base 10.
 *
 * @param s a string to check
 * @return true if the string is a valid integer, false otherwise
 */
public static boolean isInteger(String s) {
    if (s == null) {
        return false;
    }
    Scanner sc = new Scanner(s.trim());
    if (!sc.hasNextInt()) {
        return false;
    }
    sc.nextInt();
    return !sc.hasNext();
}
 
Example 5
Source File: ProcessBuilderTest.java    From java-core-learning-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ProcessBuilder pb = new ProcessBuilder("cmd","/c","ipconfig/all");
    Process p = pb.start();

    Scanner scanner = new Scanner(p.getInputStream());
    while (scanner.hasNext())
        System.out.println(scanner.next());
    scanner.close();
}
 
Example 6
Source File: Logger.java    From Everest with Apache License 2.0 5 votes vote down vote up
private String readFile(InputStream stream) {
    StringBuilder builder = new StringBuilder();
    Scanner scanner = new Scanner(stream);

    while (scanner.hasNext()) {
        builder.append(scanner.nextLine());
        builder.append("\n");
    }
    scanner.close();

    return builder.toString();
}
 
Example 7
Source File: Messaging.java    From quickstart-java with Apache License 2.0 5 votes vote down vote up
/**
 * Read contents of InputStream into String.
 *
 * @param inputStream InputStream to read.
 * @return String containing contents of InputStream.
 * @throws IOException
 */
private static String inputstreamToString(InputStream inputStream) throws IOException {
  StringBuilder stringBuilder = new StringBuilder();
  Scanner scanner = new Scanner(inputStream);
  while (scanner.hasNext()) {
    stringBuilder.append(scanner.nextLine());
  }
  return stringBuilder.toString();
}
 
Example 8
Source File: ObservationReader.java    From HMMRATAC with GNU General Public License v3.0 5 votes vote down vote up
private List<?> readReal(Scanner inFile){
	List<ObservationReal> obseq = new ArrayList<ObservationReal>();
	while(inFile.hasNext()){
		ObservationReal o = new ObservationReal(inFile.nextDouble());
		obseq.add(o);
	}
	return obseq;
}
 
Example 9
Source File: NumberUtils.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param str string to check
 * @return whether the string is a double value
 */
public static boolean isDouble(String str) {
    if (str == null) {
        return false;
    }
    Scanner s = new Scanner(str.trim());
    if (!s.hasNextDouble()) {
        return false;
    }
    s.nextDouble();
    return !s.hasNext();
}
 
Example 10
Source File: UiFontTest.java    From mini2Dx with Apache License 2.0 5 votes vote down vote up
private String readFromResource(String path) {
	final Scanner scanner = new Scanner(UiFont.class.getResourceAsStream(path));
	final StringBuilder result = new StringBuilder();

	while(scanner.hasNext()) {
		result.append(scanner.next());
	}
	scanner.close();
	return result.toString();
}
 
Example 11
Source File: TemplateManager.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a template's contents from the specified location
 *
 * @param name The location of the template
 * @return The raw template contents
 */
public String readTemplate(String name) {
    try {
        Reader reader = getTemplateReader(name);
        if (reader == null) {
            throw new RuntimeException("no file found");
        }
        Scanner s = new Scanner(reader).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    throw new RuntimeException("can't load template " + name);
}
 
Example 12
Source File: UpgradeService.java    From catnut with MIT License 5 votes vote down vote up
private void checkout() throws Exception {
	URL url = new URL(METADATA_URL);
	InputStream inputStream = url.openStream();
	Scanner in = new Scanner(inputStream).useDelimiter("\\A");
	if (in.hasNext()) {
		JSONObject metadata = new JSONObject(in.next());
		PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
		if (info.versionCode < metadata.optInt(FIELD_VERSION_CODE)) {
			Notification.InboxStyle style = new Notification.InboxStyle(mBuilder);
			String size = metadata.optString("size");
			style.setBigContentTitle(getString(R.string.find_new_version, size));
			JSONArray messages = metadata.optJSONArray("messages");
			for (int i = 0; i < messages.length(); i++) {
				style.addLine(messages.optString(i));
			}
			// download&upgrade intent
			Intent download = new Intent(this, UpgradeService.class);
			download.setAction(ACTION_DOWNLOAD);
			download.putExtra(DOWNLOAD_LINK, metadata.optString(DOWNLOAD_LINK));
			PendingIntent piDownload = PendingIntent.getService(this, 0, download, 0);
			mBuilder.addAction(R.drawable.ic_stat_download_dark, getString(R.string.down_load_and_upgrade), piDownload);
			// dismiss notification
			Intent dismiss = new Intent(this, UpgradeService.class);
			dismiss.setAction(ACTION_DISMISS);
			PendingIntent piDismiss = PendingIntent.getService(this, 0, dismiss, 0);
			mBuilder.addAction(R.drawable.ic_stat_content_remove_dark, getString(R.string.not_upgrade_now), piDismiss);
			// show it.
			mBuilder.setTicker(getString(R.string.find_new_version));
			mNotificationManager.notify(ID, mBuilder.setDefaults(Notification.DEFAULT_ALL).build());
		} else {
			new Handler(Looper.getMainLooper()).post(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(UpgradeService.this, getString(R.string.already_updated), Toast.LENGTH_SHORT).show();
				}
			});
		}
	}
	in.close();
}
 
Example 13
Source File: FcmSender.java    From capillary with Apache License 2.0 5 votes vote down vote up
private static String inputstreamToString(InputStream inputStream) throws IOException {
  StringBuilder stringBuilder = new StringBuilder();
  Scanner scanner = new Scanner(inputStream);
  while (scanner.hasNext()) {
    stringBuilder.append(scanner.nextLine());
  }
  return stringBuilder.toString();
}
 
Example 14
Source File: PayloadSpoofer.java    From ForgeHax with MIT License 5 votes vote down vote up
private boolean isBlockedPacket(String channel, ByteBuf buffer) {
  if (IGNORE_LIST.contains(channel)) {
    return true;
  } else if ("REGISTER".equals(channel)) {
    Scanner scanner = new Scanner(new String(buffer.array()));
    scanner.useDelimiter("\\u0000");
    if (scanner.hasNext()) {
      String next = scanner.next();
      return !Strings.isNullOrEmpty(next) && IGNORE_LIST.contains(next);
    }
  }
  return false;
}
 
Example 15
Source File: IOUtils.java    From cdr-gen with MIT License 4 votes vote down vote up
public static String convertStreamToString(InputStream is, String charsetName) {
    Scanner s = new Scanner(is, charsetName).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
 
Example 16
Source File: IOUtils.java    From a with GNU General Public License v3.0 4 votes vote down vote up
public static String toString(InputStream inputStream) {
    Scanner s = new Scanner(inputStream).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
 
Example 17
Source File: CommonUtils.java    From letv with Apache License 2.0 4 votes vote down vote up
public static String streamToString(InputStream is) throws IOException {
    Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
 
Example 18
Source File: WebServiceAp.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private String parseArguments() {
    // let's try to parse JavacOptions

    String classDir = null;
    try {
        ClassLoader cl = WebServiceAp.class.getClassLoader();
        Class javacProcessingEnvironmentClass = Class.forName("com.sun.tools.javac.processing.JavacProcessingEnvironment", false, cl);
        if (javacProcessingEnvironmentClass.isInstance(processingEnv)) {
            Method getContextMethod = javacProcessingEnvironmentClass.getDeclaredMethod("getContext");
            Object tmpContext = getContextMethod.invoke(processingEnv);
            Class optionsClass = Class.forName("com.sun.tools.javac.util.Options", false, cl);
            Class contextClass = Class.forName("com.sun.tools.javac.util.Context", false, cl);
            Method instanceMethod = optionsClass.getDeclaredMethod("instance", new Class[]{contextClass});
            Object tmpOptions = instanceMethod.invoke(null, tmpContext);
            if (tmpOptions != null) {
                Method getMethod = optionsClass.getDeclaredMethod("get", new Class[]{String.class});
                Object result = getMethod.invoke(tmpOptions, "-s"); // todo: we have to check for -d also
                if (result != null) {
                    classDir = (String) result;
                }
                this.options.verbose = getMethod.invoke(tmpOptions, "-verbose") != null;
            }
        }
    } catch (Exception e) {
        /// some Error was here - problems with reflection or security
        processWarning(WebserviceapMessages.WEBSERVICEAP_PARSING_JAVAC_OPTIONS_ERROR());
        report(e.getMessage());
    }

    if (classDir == null) { // some error within reflection block
        String property = System.getProperty("sun.java.command");
        if (property != null) {
            Scanner scanner = new Scanner(property);
            boolean sourceDirNext = false;
            while (scanner.hasNext()) {
                String token = scanner.next();
                if (sourceDirNext) {
                    classDir = token;
                    sourceDirNext = false;
                } else if ("-verbose".equals(token)) {
                    options.verbose = true;
                } else if ("-s".equals(token)) {
                    sourceDirNext = true;
                }
            }
        }
    }
    if (classDir != null) {
        sourceDir = new File(classDir);
    }
    return classDir;
}
 
Example 19
Source File: ResourceUtils.java    From Dagger-2-Example with Apache License 2.0 4 votes vote down vote up
/**
 * Converts InputStream to String.
 */
public static String convertStreamToString(InputStream is) {
    Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
 
Example 20
Source File: MapFactory.java    From WATisRain with MIT License 4 votes vote down vote up
private static void handleCommandPath(Map map, Scanner scanner){
	
	String name1 = scanner.next();
	String name2 = scanner.next();
	
	// Figure out where we are, approximately first. This location will have the
	// correct waypoint, but may have the incorrect floor.
	Location roughly_loc1 = map.getLocationByID(name1);
	Location roughly_loc2 = map.getLocationByID(name2);
	
	// We can have 0 or more "connects" commands. Store them in a list.
	ArrayList<Integer> connect_floors1 = new ArrayList<>();
	ArrayList<Integer> connect_floors2 = new ArrayList<>();
	
	int pathType = Path.TYPE_OUTSIDE;
	
	// Read waypoints
	List<Waypoint> waypoints = new ArrayList<>();
	waypoints.add(roughly_loc1.getPostion());
	
	// Read until semicolon
	while(true){
		if(!scanner.hasNext()) break;
		String s = scanner.next();
		if(s.equals(";")) break;
		
		if(s.equals("p")){
			// add waypoint
			int wx = scanner.nextInt();
			int wy = scanner.nextInt();
			
			waypoints.add(new Waypoint(wx,wy));
		}
		
		if(s.equals("type")){
			String type_str = scanner.next();
			switch(type_str){
				case "inside":
					pathType = Path.TYPE_INSIDE;
					break;
				case "indoor_tunnel":
					pathType = Path.TYPE_INDOOR_TUNNEL;
					break;
				case "underground_tunnel":
					pathType = Path.TYPE_UNDERGROUND_TUNNEL;
					break;
				case "briefly_outside":
					pathType = Path.TYPE_BRIEFLY_OUTSIDE;
					break;
			}
		}
		
		if(s.equals("connects")){
			connect_floors1.add(scanner.nextInt());
			connect_floors2.add(scanner.nextInt());
		}
	}
	
	waypoints.add(roughly_loc2.getPostion());
	
	
	// No "connects" specified, then just link main floor to main floor
	if(connect_floors1.isEmpty()){
		int main_floor1 = 1;
		int main_floor2 = 1;
		Building build1 = map.getBuildingByID(name1);
		Building build2 = map.getBuildingByID(name2);
		if(build1 != null) main_floor1 = build1.getMainFloorNumber();
		if(build2 != null) main_floor2 = build2.getMainFloorNumber();
		connect_floors1.add(main_floor1);
		connect_floors2.add(main_floor2);
	}
	
	
	
	// Add a path for each "connects"
	for(int i=0; i<connect_floors1.size(); i++){
		Location loc1 = map.getLocationByID(Util.makeBuildingAndFloor(name1, connect_floors1.get(i)));
		Location loc2 = map.getLocationByID(Util.makeBuildingAndFloor(name2, connect_floors2.get(i)));

		Path path = new Path(loc1,loc2);
		path.setWaypoints(waypoints);
		path.setPathType(pathType);
		
		map.addPath(path);
	}
}