public static void main(String[] args) { Scanner s = new Scanner(System.in); int i; try { System.out.print("enter an int => "); i = s.nextInt(); } catch (InputMismatchException e) { System.out.println("Error! " + e); i = -1; } finally { s.close(); System.out.println("we're done"); } System.out.println("What is the value of i: " + i); }
/** * Prompt the user to enter a number and return it * pre: none * post: Question parameter printed, user integer input returned */ public int ask(String question) { badInput = true; do { try { System.out.print(question); int next = input.nextInt(); if (next > 0) { badInput = false; return next; } else badInput = true; } catch (InputMismatchException e) { System.out.println("Please input a positive whole number."); } input.nextLine(); } while (badInput); badInput = true; System.out.println("ERROR OCCURRED. You shouldn't see this message. Error code: 100"); return 100; }
/** * This method ask the user to input the place. * @param array. * @exception InputMismatchException : Error on the input, try again. */ @SuppressWarnings("resource") public void filteringBy(ArrayList<Wifi> array) throws InputException { try { System.out.println("Input an latitude please :"); double pointLatitude = new Scanner(System.in).nextDouble(); System.out.println("Input an longitude please :"); double pointLongitude = new Scanner(System.in).nextDouble(); System.out.println("Input a radius please (meters) :"); double radius = new Scanner(System.in).nextDouble(); if(checkLatitude(pointLatitude) && checkLongitude(pointLongitude) && radius >= 0) { EarthCoordinate pointLocation = new EarthCoordinate(pointLongitude, pointLatitude, 0.0); // Latitude 0.0 by default. new WriteKmlPlace(array, pointLocation, radius); } else throw new InputException("There is ne such latitude/longitude/radius."); } catch (InputMismatchException ex) { System.out.println("Error on the input, try again."); filteringBy(array); } }
private static JsonList parseList(Tokenizer tokens) throws InputMismatchException { JsonList list = new JsonList(); //Expect start of list ([) tokens.next(TokenCode.LSQUARE); //While not end of list while (!tokens.isNext(TokenCode.RSQUARE)) { //format: <value>, <value>, ... //Insert value into list list.add(parseValue(tokens)); if (tokens.isNext(TokenCode.COMMA)) { tokens.next(); } } //Expect end of list (]) tokens.next(TokenCode.RSQUARE); return list; }
public static int getInt(Scanner input) throws InputMismatchException{ int value = -1; boolean bad = true; do { try { value = input.nextInt(); if (value != -1 && input.nextLine().equals("")) bad = false; else System.out.println("Please enter only one integer"); } catch (InputMismatchException ex) { System.out.println("Incorrect entry. Please input only a positive integer."); input.nextLine(); } } while(bad); return value; }
public static int getInt(Scanner input, int max) throws InputMismatchException { int value = -1; boolean bad = true; do { try { value = input.nextInt(); if (value > 0 && value <= max && input.nextLine().equals("")) bad = false; else System.out.println("Please enter a valid number"); } catch (InputMismatchException ex) { System.out.println("Incorrect entry. Please input only a positive integer."); input.nextLine(); } } while(bad); return value; }
/** * Prompts a user to select a command from a list of commands. * @param thePrompt the prompt * @param theCommands the list of commands * @return the selected command * @throws NullPointerException if the prompt or command array is null */ protected Command getCommand(final String thePrompt, final Command[] theCommands) { displayNumberedList(Arrays.stream(Objects.requireNonNull(theCommands)).map(Object::toString).toArray(String[]::new)); try { int commandNumber = getInteger(Objects.requireNonNull(thePrompt), 1, theCommands.length); if(commandNumber > 0 && commandNumber <= theCommands.length) { return theCommands[commandNumber - 1]; } else { return null; } } catch(final InputMismatchException e) { print("Command not recognized."); return getCommand(thePrompt, theCommands); } }
/** * Validate otp if chosen mode is mobile */ @Override public void validateOtpMMode(String userId, String otp) throws ValidationException { MemcacheService cache = AppFactory.get().getMemcacheService(); if (cache.get("OTP_" + userId) == null) { xLogger.warn("OTP expired or already used to generate new password for " + userId); throw new InputMismatchException("OTP not valid"); } if (otp.equals(cache.get("OTP_" + userId))) { cache.delete("OTP_" + userId); } else { xLogger.warn("Wrong OTP entered for " + userId); throw new ValidationException("UA002",userId); } }
private void validateInputs() throws InputMismatchException { String title = titleTextField.getText(); if (title.isEmpty()) { throw new InputMismatchException("Please specify a title."); } try { int width = Integer.parseInt(widthTextField.getText()); int height = Integer.parseInt(heightTextField.getText()); if (width < 1 || width > 10000) { throw new NumberFormatException(); } if (height < 1 || height > 10000) { throw new NumberFormatException(); } } catch (NumberFormatException exception) { throw new InputMismatchException("The values for width and height must be integer numbers between 1 and 10000."); } }
private void exportBitmap() { try { validateInputs(); int originalWidth = document.getWidth(); int width = Integer.parseInt(widthTextField.getText()); double scaleFactor = (double) width / (double) originalWidth; if (mainController.getGUIController().exportBitmap((Stage) this.getWindow(), scaleFactor)) { close(); } } catch (InputMismatchException exception) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.initOwner(getWindow()); alert.setContentText(exception.getMessage()); alert.showAndWait(); } }
private void validateInputs() throws InputMismatchException { try { int width = Integer.parseInt(widthTextField.getText()); int height = Integer.parseInt(heightTextField.getText()); if (width < 1 || width > 10000) { throw new NumberFormatException(); } if (height < 1 || height > 10000) { throw new NumberFormatException(); } } catch (NumberFormatException exception) { throw new InputMismatchException("The values for width and height must be integer numbers between 1 and 10000."); } }
public void run() { sc = new Scanner(System.in); clear(); drawLifeInvader(); drawSeparator(); show("Hello young entrepreneur, today you're gonna change the world !"); show("What's the name of your socialNetwork ?"); show("Your choice : "); String input = ""; do { try { input = sc.nextLine(); } catch (InputMismatchException e) { show("Please select a correct option"); sc.next(); } } while (input.equals("")); socialNetworkName = input; controller.setUpSocialNetwork(input); isServer(); }
/** * Run system calibration * * @throws IOException * @throws InputMismatchException */ public long runCalibration() throws InputMismatchException, IOException { final int ITERATIONS = 10; long total = 0; for (int i = 0; i < ITERATIONS; i++) { long calBegin = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); gen.generateText(PARAGRAPH, LINE_WIDTH, TOTAL_CHARS, baos); baos.close(); long calEnd = System.currentTimeMillis(); total = calEnd - calBegin; } log.debug("Calibration: {} ms", total / ITERATIONS); return total / ITERATIONS; }
public static int convertInt(byte[] bytes) { if (bytes.length != NekoIOConstants.INT_LENGTH) { throw new InputMismatchException( "Number of bytes provided does not match NekoIOConstants.INT_LENGTH"); } int val = 0; for (int i = 0; i < NekoIOConstants.INT_LENGTH; i++) { val <<= 8; if (NekoIOConstants.BIG_ENDIAN) { val |= Byte.toUnsignedInt(bytes[i]); } else { val |= Byte.toUnsignedInt(bytes[NekoIOConstants.INT_LENGTH - 1 - i]); } } log.log(Level.FINEST, String.format("%d", val)); return val; }
private int next() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; }
public int nextInt() { int c = skipWhileSpace(); int sgn = 1; if (c == '-') { sgn = -1; c = next(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; }
public long nextLong() { int c = skipWhileSpace(); long sgn = 1; if (c == '-') { sgn = -1; c = next(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c-'0'; c = next(); } while (!isSpaceChar(c)); return res*sgn; }
private void characterTextFieldKeyReleased(java.awt.event.KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_ENTER && isEditable()) { try { String characterText = characterTextField.getText(); if (characterText.length() == 0) { throw new InputMismatchException("Empty value not valid"); } if (characterText.length() > 1) { throw new InputMismatchException("Only single character allowed"); } byte[] bytes = characterText.getBytes(codeArea.getCharset()); System.arraycopy(bytes, 0, valuesCache, 0, bytes.length); modifyValues(bytes.length); updateValues(); } catch (InputMismatchException ex) { showException(ex); } } }
@Test public void testCompletableFuturePromiseWithException() { CompletableFuture<Integer> completableFuture = new CompletableFuture<>(); completableFuture.handleAsync((item, throwable) -> { if (throwable != null) { throwable.printStackTrace(); return -1; } else { return item; } }); System.out.println("Processing something else"); completableFuture.completeExceptionally( new InputMismatchException("Just for fun")); }
/** * waits for a user input and requires a Integer value * * @return the given int value */ @Override public int getIntInput() { boolean inputOk = false; Integer intInput = null; do { try { intInput = sc.nextInt(); inputOk = true; } catch (InputMismatchException e) { this.printErrorln("Please define an integer."); this.resetScanner(); } } while(!inputOk); return intInput; }
/** * waits for a user input and requires a String value * * @return the given String value */ @Override public String getStringInput() { boolean inputOk = false; String stringInput = null; do { try { stringInput = sc.nextLine(); if (stringInput == null || stringInput.isEmpty()) { throw new InputMismatchException("Defined value is not valid"); } inputOk = true; } catch (InputMismatchException e) { this.printErrorln("Please define a string."); this.resetScanner(); } } while(!inputOk); return stringInput; }
@Override public InputToParser readInput(final String line) { final List<Category> result = new ArrayList<>(); final String[] goldEntries = line.split(" "); final List<InputWord> words = new ArrayList<>(goldEntries.length); final List<List<ScoredCategory>> supertags = new ArrayList<>(); for (final String entry : goldEntries) { final String[] goldFields = entry.split("\\|"); if (goldFields[0].equals("\"")) { continue; // TODO quotes } if (goldFields.length < 3) { throw new InputMismatchException("Invalid input: expected \"word|POS|SUPERTAG\" but was: " + entry); } final String word = goldFields[0]; final String pos = goldFields[1]; final Category category = Category.valueOf(goldFields[2]); words.add(new InputWord(word, pos, null)); result.add(category); supertags.add(Collections.singletonList(new ScoredCategory(category, Double.MAX_VALUE))); } return new InputToParser(words, result, supertags, false); }
@Override public InputToParser readInput(final String line) { final String[] taggedEntries = line.split(" "); final List<InputWord> inputWords = new ArrayList<>(taggedEntries.length); for (final String entry : taggedEntries) { final String[] taggedFields = entry.split("\\|"); if (taggedFields.length < 2) { throw new InputMismatchException("Invalid input: expected \"word|POS\" but was: " + entry); } if (taggedFields[0].equals("\"")) { continue; // TODO quotes } inputWords.add(new InputWord(taggedFields[0], taggedFields[1], null)); } return new InputToParser(inputWords, null, null, false); }
@Override public InputToParser readInput(final String line) { final String[] taggedEntries = line.split(" "); final List<InputWord> inputWords = new ArrayList<>(taggedEntries.length); for (final String entry : taggedEntries) { final String[] taggedFields = entry.split("\\|"); if (taggedFields[0].equals("\"")) { continue; // TODO quotes } if (taggedFields.length < 3) { throw new InputMismatchException("Invalid input: expected \"word|POS|NER\" but was: " + entry + "\n" + "The C&C can produce this format using: \"bin/pos -model models/pos | bin/ner -model models/ner -ofmt \"%w|%p|%n \\n\"\""); } inputWords.add(new InputWord(taggedFields[0], taggedFields[1], taggedFields[2])); } return new InputToParser(inputWords, null, null, false); }
private static void doViewMenu(Path p) throws IOException{ try(Scanner fin = new Scanner(new BufferedInputStream( new FileInputStream(p.toFile())),"UTF-8")){ System.out.println("-----------------VIEW RECORDS-----------------"); //Records must be separated fin.useDelimiter("\\s*,\\s*|\\h*\\v+"); while(fin.hasNext()){ System.out.println(" ID: " + fin.nextInt()); System.out.println(" Last Name: " + fin.next()); System.out.println(" First Name: " + fin.next()); System.out.printf(" Height (in meters): %.2f%n", fin.nextFloat()); System.out.println(""); } }catch (InputMismatchException ex){ throw new IOException("Invalid file format",ex); }finally{ System.out.println("----------------------------------------------"); } }
@Override public double getDistance(Datum d1, Datum d2){ double distance = 0.0d; double [] pt1 = d1.getVector(); double [] pt2 = d2.getVector(); if (pt1.length != pt2.length) { throw new InputMismatchException(); } double sumOfSquares=0; int size = pt1.length; for (int i=0; i<size; i++){ sumOfSquares+=Math.pow((pt1[i]-pt2[i]),2); } distance = Math.sqrt(sumOfSquares); return distance; }
@Override public double getDistance(double [] pt1, double [] pt2){ double distance = 0.0; if (pt1.length != pt2.length) { System.err.println("Point 1 length = " + pt1.length + " != " + pt2.length ); throw new InputMismatchException(); } double sumOfSquares=0.0; int size = Math.min(pt1.length,pt2.length) ; for (int i=0; i<size; i++){ sumOfSquares+=Math.pow((pt1[i]-pt2[i]),2); } distance = Math.sqrt(sumOfSquares); return distance; }
public static TypeDescriptor fromRaw(String raw) { final int length = raw.length(); int dimensions = raw.lastIndexOf('[') + 1; final String subType = raw.substring(dimensions); final TypeDescriptor simpleType; if (subType.equals("V")) { simpleType = VoidTypeDescriptor.voidTypeDescriptor; } else if (subType.startsWith("L") && subType.endsWith(";")) { simpleType = fromClassName(subType.substring(1, length - dimensions - 1)); } else { simpleType = PrimitiveTypeDescriptor.fromRaw(subType); if (simpleType == null) { throw new InputMismatchException("Invalid type descriptor: " + raw); } } if (dimensions > 0) { return new ArrayTypeDescriptor(simpleType, dimensions); } return simpleType; }
private float diruaEskatu(){ float n; boolean ezAmaitu = true; do { try { System.out.println("Sartu diru kantitate bat: "); n = sc.nextFloat(); ezAmaitu=false; } catch (InputMismatchException e) { sc.nextLine(); n = 0; System.out.println("Sartu duzuna ez da diru kantitate bat."); } }while (ezAmaitu); return n; }
public long nextLong () { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; }
public int nextInt () { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; }
public boolean load(String filename, boolean eraseOld) { try { Scanner s = new Scanner(new BufferedReader(new FileReader(filename))); if (eraseOld) deleteFullGraph(); graph.load(s); if (TextureEditor.GL_ENABLED) TextureEditor.INSTANCE.m_OpenGLPreviewPanel.load(s); repaint(); return true; } catch (FileNotFoundException e) { Logger.logError(this, "Could not load " + filename); return false; } catch (InputMismatchException ime) { ime.printStackTrace(); Logger.logError(this, "Could not load " + filename); return false; } }
@Override public InputToParser readInput(String line) { // Pierre NNP 0 N/N 0.99525070603732 N 0.0026450007306822|Vinken NNP 0 N 0.70743834018551 S/S 0.14043752457392 List<List<SyntaxTreeNodeLeaf>> supertags = new ArrayList<List<SyntaxTreeNodeLeaf>>(); String[] split = line.split("\\|"); List<InputWord> words = new ArrayList<InputWord>(split.length); for (String wordTags : split) { List<SyntaxTreeNodeLeaf> entries = new ArrayList<SyntaxTreeNodeLeaf>(); String[] fields = wordTags.split("(\t| )+"); String word = fields[0]; if (fields.length < 5) throw new InputMismatchException("Expected input using the C&C with output format --ofmt \"%w\\t%p\\t%S|\\n\" but was: " + line); words.add(new InputWord(word)); for (int i=3; i < fields.length; i=i+2) { Category cat = Category.valueOf(fields[i]); entries.add(nodeFactory.makeTerminal(word, cat, fields[1], null, Math.log(Double.valueOf(fields[i + 1])), entries.size())); } supertags.add(entries); } return new InputToParser(words, null, supertags, true); }
@Override public InputToParser readInput(String line) { List<Category> result = new ArrayList<Category>(); String[] goldEntries = line.split(" "); List<InputWord> words = new ArrayList<InputWord>(goldEntries.length); List<List<SyntaxTreeNodeLeaf>> supertags = new ArrayList<List<SyntaxTreeNodeLeaf>>(); for (String entry : goldEntries) { String[] goldFields = entry.split("\\|"); if (goldFields[0].equals("\"")) continue ; //TODO quotes if (goldFields.length < 3) throw new InputMismatchException("Invalid input: expected \"word|POS|SUPERTAG\" but was: " + entry); String word = goldFields[0]; String pos = goldFields[1]; Category category = Category.valueOf(goldFields[2]); words.add(new InputWord(word)); result.add(category); supertags.add(Arrays.asList(nodeFactory.makeTerminal(word, category, pos, null, 1.0, supertags.size()))); } return new InputToParser(words, result, supertags, false); }