List of usage examples for java.util Scanner hasNext
public boolean hasNext()
From source file:ReversePolishNotation.java
/** * This method will calculate the answer of the given Reverse Polar Notation * equation. All exceptions are thrown to the parent for handling. * // www . j a va2s.c o m * @param input * is the equation entered by the user * @throws EmptyRPNException * when there is no RPN equation to be evaluated. * @throws RPNDivideByZeroException * when the RPN equation attempts to divide by zero. * @throws RPNUnderflowException * when the RPN equation has a mathematical operator before * there are enough numerical values for it to evaluate. * @throws InvalidRPNException * when the RPN equation is a String which is unable to be * manipulated. * @throws RPNOverflowException * when the RPN equation has too many numerical values and not * enough mathematical operators with which to evaluate them. * @return the top item of the stack; the calculated answer of the Reverse * Polish Notation equation */ public static double calcRPN(String input) { // eliminate any leading or trailing whitespace from input input = input.trim(); // scanner to manipulate input and stack to store double values String next; Stack<Double> stack = new Stack<Double>(); Scanner scan = new Scanner(input); // loop while there are tokens left in scan while (scan.hasNext()) { // retrieve the next token from the input next = scan.next(); // see if token is mathematical operator if (nextIsOperator(next)) { // ensure there are enough numbers on stack if (stack.size() > 1) { if (next.equals("+")) { stack.push((Double) stack.pop() + (Double) stack.pop()); } else if (next.equals("-")) { stack.push(-(Double) stack.pop() + (Double) stack.pop()); } else if (next.equals("*")) { stack.push((Double) stack.pop() * (Double) stack.pop()); } else if (next.equals("/")) { double first = stack.pop(); double second = stack.pop(); if (first == 0) { System.out.println("The RPN equation attempted to divide by zero."); } else { stack.push(second / first); } } } else { System.out.println( "A mathematical operator occured before there were enough numerical values for it to evaluate."); } } else { try { stack.push(Double.parseDouble(next)); } catch (NumberFormatException c) { System.out.println("The string is not a valid RPN equation."); } } } if (stack.size() > 1) { System.out.println( "There too many numbers and not enough mathematical operators with which to evaluate them."); } return (Double) stack.pop(); }
From source file:UtilFunctions.java
public static String[] parseFileTypes(String inputString) { //ArrayList to store each parsed filetype ArrayList<String> fileTypes = new ArrayList<>(); //Scanner to iterate over the string filetype by filetype Scanner in = new Scanner(inputString); in.useDelimiter("[,] | [, ]"); //Iterate over the string while (in.hasNext()) { fileTypes.add(in.next());/*from w w w .j a va 2s.c om*/ } if (fileTypes.size() > 0) { //Generate an array from the ArrayList String[] returnArray = new String[fileTypes.size()]; returnArray = fileTypes.toArray(returnArray); //Return that magnificent array return returnArray; } else { return null; } }
From source file:cpd3314.buildit12.CPD3314BuildIt12.java
/** * Build a program that asks the user for a filename. It then reads a file * line-by-line, and outputs its contents in uppercase. * * Make sure that the program exits gracefully when the file does not exist. * */// w ww . ja v a2 s .co m public static void doBuildIt1() { // Prompt the User for a Filename Scanner kb = new Scanner(System.in); System.out.println("Filename: "); String filename = kb.next(); try { // Attempt to Access the File, this may cause an Exception File file = new File(filename); Scanner input = new Scanner(file); // Iterate through the File and Output in Upper Case while (input.hasNext()) { System.out.println(input.nextLine().toUpperCase()); } } catch (IOException ex) { // If the File is Not Found, Tell the User and Exit Gracefully System.err.println("File not found: " + filename); } }
From source file:Main.java
/** * @return A map of all storage locations available */// w ww. java 2 s .c o m public static Map<String, File> getAllStorageLocations() { Map<String, File> map = new HashMap<String, File>(10); List<String> mMounts = new ArrayList<String>(10); List<String> mVold = new ArrayList<String>(10); mMounts.add("/mnt/sdcard"); mVold.add("/mnt/sdcard"); try { File mountFile = new File("/proc/mounts"); if (mountFile.exists()) { Scanner scanner = new Scanner(mountFile); while (scanner.hasNext()) { String line = scanner.nextLine(); if (line.startsWith("/dev/block/vold/")) { String[] lineElements = line.split(" "); String element = lineElements[1]; // don't add the default mount path // it's already in the list. if (!element.equals("/mnt/sdcard")) mMounts.add(element); } } } } catch (Exception e) { e.printStackTrace(); } try { File voldFile = new File("/system/etc/vold.fstab"); if (voldFile.exists()) { Scanner scanner = new Scanner(voldFile); while (scanner.hasNext()) { String line = scanner.nextLine(); if (line.startsWith("dev_mount")) { String[] lineElements = line.split(" "); String element = lineElements[2]; if (element.contains(":")) element = element.substring(0, element.indexOf(":")); if (!element.equals("/mnt/sdcard")) mVold.add(element); } } } } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < mMounts.size(); i++) { String mount = mMounts.get(i); if (!mVold.contains(mount)) mMounts.remove(i--); } mVold.clear(); List<String> mountHash = new ArrayList<String>(10); for (String mount : mMounts) { File root = new File(mount); if (root.exists() && root.isDirectory() && root.canWrite()) { File[] list = root.listFiles(); String hash = "["; if (list != null) { for (File f : list) { hash += f.getName().hashCode() + ":" + f.length() + ", "; } } hash += "]"; if (!mountHash.contains(hash)) { String key = SD_CARD + "_" + map.size(); if (map.size() == 0) { key = SD_CARD; } else if (map.size() == 1) { key = EXTERNAL_SD_CARD; } mountHash.add(hash); map.put(key, root); } } } mMounts.clear(); if (map.isEmpty()) { map.put(SD_CARD, Environment.getExternalStorageDirectory()); } return map; }
From source file:adviewer.util.JSONIO.java
/** * Take in file and return one string of json data * //from w w w. jav a2 s . c o m * @return * @throws IOException */ public static String readJSONFile(File inFile) { String readFile = ""; try { File fileIn = inFile; //if the file is not there then create the file if (fileIn.createNewFile()) { System.out.println(fileIn + " was created "); } FileReader fr = new FileReader(fileIn); Scanner sc = new Scanner(fr); while (sc.hasNext()) { readFile += sc.nextLine().trim(); } return readFile; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println( readFile ); return readFile; }
From source file:org.hancel.http.HttpUtils.java
private static JSONObject execute(String base, List<NameValuePair> params, String method) throws IOException, JSONException { URL url;// w w w.j av a2s . c o m HttpURLConnection urlConnection = null; if (method.equals("GET")) { url = new URL(base + getQuery(params)); urlConnection = (HttpURLConnection) url.openConnection(); } try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); Scanner s = new Scanner(in).useDelimiter("\\A"); String parseString = s.hasNext() ? s.next() : ""; in.close(); return new JSONObject(parseString); } finally { urlConnection.disconnect(); } }
From source file:org.n52.util.CommonUtilities.java
public static String readResource(InputStream res) { Scanner sc = new Scanner(res); StringBuilder sb = new StringBuilder(); while (sc.hasNext()) { sb.append(sc.nextLine());/*from w w w . j ava2 s. c o m*/ sb.append(NEW_LINE_CHAR); } sc.close(); return sb.toString(); }
From source file:edu.msu.cme.rdp.unifrac.Unifrac.java
private static Map<String, UnifracSample> readSampleMap(String sampleFile) throws IOException { Map<String, UnifracSample> ret = new HashMap(); Map<String, MCSample> sampleMap = new HashMap(); int lineno = 1; Scanner s = new Scanner(new File(sampleFile)).useDelimiter("\n"); while (s.hasNext()) { String line = s.next().trim(); if (line.equals("")) { continue; }/*from w ww . ja v a 2s . c om*/ String[] tokens = line.split("\\s+"); if (tokens.length < 2) { throw new IOException("Failed to parse sample mapping file (lineno=" + lineno + ")"); } String sampleName = tokens[1]; String seqName = tokens[0]; int sampleCount = 1; try { sampleCount = Integer.parseInt(tokens[2]); } catch (Exception e) { } if (!sampleMap.containsKey(sampleName)) sampleMap.put(sampleName, new MCSample(sampleName)); UnifracSample unifracSample = new UnifracSample(); unifracSample.sample = sampleMap.get(sampleName); unifracSample.count = sampleCount; ret.put(seqName, unifracSample); lineno++; } s.close(); return ret; }
From source file:org.apache.oodt.cas.protocol.http.util.HttpUtils.java
public static String readUrl(HttpURLConnection conn) throws IOException { // create URL source reader Scanner scanner = new Scanner(conn.getInputStream()); // Read in link StringBuilder sb = new StringBuilder(""); while (scanner.hasNext()) { sb.append(scanner.nextLine());//ww w .j ava 2 s . co m } return sb.toString(); }
From source file:azureml_besapp.AzureML_BESApp.java
/** * Read the JSON schema from the file rrsJson.json * /*from w w w . jav a 2s.c o m*/ * @param filename It expects a fully qualified file name that contains input JSON file */ public static void readJson(String filename) { try { File apiFile = new File(filename); Scanner sc = new Scanner(apiFile); jsonBody = ""; while (sc.hasNext()) { jsonBody += sc.nextLine() + "\n"; } } catch (Exception e) { System.out.println(e.toString()); } }