java.util.InputMismatchException Java Examples

The following examples show how to use java.util.InputMismatchException. 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: FileParserSingleton.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private void readSupportedFilesList(BufferedReader fileList) throws IOException
{
	String line;
	String[] entry;
	while((line = fileList.readLine()) != null)
	{
		if (!line.trim().startsWith("#"))
		{
			entry=line.split("\\t");
			if(entry.length!=3)
			{
				throw new InputMismatchException("The supported file List "+ supportedFilesListPath+" has errors in its format in line: "+line); 
			}
			supportedFiles.put(entry[1], entry[0]);
			contentHandlerType.put(entry[1], entry[2]);
		}
	}
}
 
Example #2
Source File: Road_ and_Libraries.java    From interview-preparation-kit with MIT License 6 votes vote down vote up
int ni()
{
	int ans = 0;
	int sign = 1;
	int x = nextNonSpace();
	if(x=='-')
	{
		sign = -1;
		x = nextByte();
	}
	while(!isSpaceChar(x))
	{
		if(isDigit(x))
		{
			ans = ans*10 + x -'0';
			x = nextByte();
		}
		else
			throw new InputMismatchException();
	}
	return sign*ans;
}
 
Example #3
Source File: Road_ and_Libraries.java    From interview-preparation-kit with MIT License 6 votes vote down vote up
long nl()
{
	long ans = 0;
	long sign = 1;
	int x = nextNonSpace();
	if(x=='-')
	{
		sign = -1;
		x = nextByte();
	}
	while(!isSpaceChar(x))
	{
		if(isDigit(x))
		{
			ans = ans*10 + x -'0';
			x = nextByte();
		}
		else
			throw new InputMismatchException();
	}
	return sign*ans;
}
 
Example #4
Source File: DecimalToBinaryConversion.java    From Mathematics with MIT License 6 votes vote down vote up
public static void main(String[] args) {

   try{
   Scanner scan = new Scanner (System.in);
   
   //Prompt user for a decimal number to convert to binary
   System.out.println("Please input a decimal number to convert...");
   int numToConvert = scan.nextInt();
   ArrayList <Integer> convertedNum=conversion(numToConvert);
   System.out.print("Decimal number: "+numToConvert + " is equal to binary number: ");
   print(convertedNum);
 

   }catch(InputMismatchException ex){
     System.err.println("Please provide only numbers (no text). Restart the program and try again!");
     main(new String[0]);
   }
   
 }
 
Example #5
Source File: App.java    From JYTB with GNU General Public License v3.0 6 votes vote down vote up
private static void setWatchSeconds() {
    boolean validated = false;

    while (!validated) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("How long would you like to watch the video for, IN SECONDS? (Must be greater than 30 seconds)");
        System.out.print("->  ");
        try {
            int seconds = scanner.nextInt();

            if (seconds < 30) {
                System.out.println(AnsiColors.ANSI_BRIGHT_RED + "Invalid Timeframe" + AnsiColors.ANSI_RESET);
                validated = false;
            }
            else {
                watchLength = seconds;
                validated = true;
            }
        } catch (InputMismatchException e) {
            System.out.println(AnsiColors.ANSI_BRIGHT_RED + "Invalid Timeframe" + AnsiColors.ANSI_RESET);
            validated = false;
        }
    }
}
 
Example #6
Source File: DecibinaryNumbers.java    From interview-preparation-kit with MIT License 6 votes vote down vote up
public long readLong() {
    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;
}
 
Example #7
Source File: DecibinaryNumbers.java    From interview-preparation-kit with MIT License 6 votes vote down vote up
public int read() {
    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++];
}
 
Example #8
Source File: Road_ and_Libraries.java    From interview-preparation-kit with MIT License 6 votes vote down vote up
int nextByte()
{
	if(bufLength==-1)
		throw new InputMismatchException();
	if(bufCurrent>=bufLength)
	{
		bufCurrent = 0;
		try
		{bufLength = inputStream.read(bufferArray);}
		catch(IOException e)
		{ throw new InputMismatchException();}
		if(bufLength<=0)
			return -1;
	}
	return bufferArray[bufCurrent++];
}
 
Example #9
Source File: fibonacci.java    From Mathematics with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    
   try{
        Scanner scan = new Scanner (System.in);
        //Prompt user for a number 
        System.out.println("Give a positive integer number: ");
        int num=scan.nextInt(); 
        if(num<0)throw new InputMismatchException();
        if(isFibo(num))System.out.println(num+" is a Fibonacci number!");
        else System.out.println(num+" is not a Fibonacci number!");
        
     }
    catch (InputMismatchException ex){
      System.err.println("Please provide only positive integer numbers (no text or negative numbers). Restart the program and try again!");
      main(new String[0]);
    }
}
 
Example #10
Source File: SpecialTriangles.java    From Mathematics with MIT License 6 votes vote down vote up
public static void main(String[] args) {
        
    try{
        Scanner scan = new Scanner (System.in);
    
        System.out.println("Special Triangles");
        //Prompt user to choose a special triangle 
        System.out.println("Choose what you want:\n 1:45 45 90 triangle \n 2:30 60 90 triangle");
        int choise = scan.nextInt();
        if(choise!=1 && choise!=2 )
           throw new InputMismatchException();
        switch(choise){
                case 1: triangle45();break;
                case 2: triangle6090();break;
                
        }
                
                
        
        
}
    catch (InputMismatchException ex){
        System.err.println("Please choose between 1 or 2. Restart the program and try again!");
        main(new String[0]);
    }
}
 
Example #11
Source File: logarithms.java    From Mathematics with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    
    

    try{
        Scanner scan = new Scanner (System.in);
    
    //Prompt user for a decimal number to convert to binary
    System.out.println("Choose which base you prefer: 2 or 10 ");
    int base = scan.nextInt();
    switch (base){
        case 2 : logarithm(base);break;
        case 10: logarithm(base);break;
        default: System.out.println("Invalid Choice.\nExiting");exit();
    }    
    }
    catch (InputMismatchException ex){
      System.err.println("Please provide only numbers (no text). Restart the program and try again!");
      main(new String[0]);
    }


}
 
Example #12
Source File: lcm.java    From Mathematics with MIT License 6 votes vote down vote up
public static void main(String[] args){
    
    
    try{
        Scanner scan=new Scanner(System.in);
    //Prompt user to give two integer numbers:
        System.out.println("Give two positive integer numbers!");
    int a=scan.nextInt();
    int b=scan.nextInt();
    if(a<0 || b<0)throw(new InputMismatchException());
    int lcm=lcm(a,b);
        System.out.println("Least Common Multiple of "+a+" and "+b+" is: "+lcm);
        
    
    }catch (InputMismatchException ex){
        System.err.println("Please give two positive integer numbers. Restart the program and try again!");
        main(new String[0]);
    }
}
 
Example #13
Source File: TextView.java    From public with Apache License 2.0 6 votes vote down vote up
@Override
public void createView() {
  System.out.println("\n\n=== Rock-paper-scissors ====");

  GameType[] gameTypes = model.getGameTypes();
  for (int i = 0; i < gameTypes.length; ++i) {
    System.out.println(i + ": " + gameTypes[i]);
  }

  while (true) {

    System.out.print("Select a game: ");
    Scanner sc = new Scanner(System.in);

    try {
      int gameType = sc.nextInt();
      controller.startGame(gameTypes[gameType]);

      break; // everything is fine
    } catch (InputMismatchException | ArrayIndexOutOfBoundsException e) {
      String errorMsg = "Game type should be a number from 0 to " + (gameTypes.length - 1) + "\n";

      System.err.println(errorMsg);
    }
  }
}
 
Example #14
Source File: TextView.java    From public with Apache License 2.0 6 votes vote down vote up
@Override
public void createView() {
  System.out.println("\n\n=== Rock-paper-scissors ====");

  GameType[] gameTypes = model.getGameTypes();
  for (int i = 0; i < gameTypes.length; ++i) {
    System.out.println(i + ": " + gameTypes[i]);
  }

  while (true) {

    System.out.print("Select a game: ");
    Scanner sc = new Scanner(System.in);

    try {
      int gameType = sc.nextInt();
      controller.startGame(gameTypes[gameType]);

      break; // everything is fine
    } catch (InputMismatchException | ArrayIndexOutOfBoundsException e) {
      String errorMsg = "Game type should be a number from 0 to " + (gameTypes.length - 1) + "\n";

      System.err.println(errorMsg);
    }
  }
}
 
Example #15
Source File: DocumentationClassifierSingleton.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private DocumentationClassifierSingleton() {
	logger = (OssmeterLogger) OssmeterLogger.getLogger("nlp.classifiers.documentation");
	try {
		String[] filesToRead = loadFile(indexName).split("\n");
		classesRegex = new HashMap<String,List<Pattern>>(filesToRead.length);
		for(String fileName : filesToRead)
		{
			if(fileName.isEmpty())
				continue;
			List<Pattern> patterns = new ArrayList<Pattern>(1);
			for(String regex : loadFile(fileName+".txt").split("\n"))
			{
				patterns.add(Pattern.compile(regex));
			}
			classesRegex.put(fileName, patterns);
			logger.info("Regex for "+fileName + " has been loaded.");
		}
	} catch (InputMismatchException | IOException e) {
		logger.error("Error while loading the indexing mappings:", e);
		e.printStackTrace();
	}
}
 
Example #16
Source File: Mapping.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Mapping()
{
	logger = (OssmeterLogger) OssmeterLogger.getLogger("indexing.bugs.mapping");
	String documentType;
	Pattern versionFinder = Pattern.compile("\"mapping_version\"\\s*:\\s*\"([^\"]+)\"");
	mappings=new HashMap<String,MappingStorage>();
	try {
		String[] mappingsToRead = loadFile(dictionnaryName).split("\n");
		
		for(String mappingName : mappingsToRead)
		{
			if(mappingName.isEmpty())
				continue;
			documentType=mappingName.replace("_", ".");
			mappings.put(documentType, loadMapping(mappingName+".json", versionFinder));
			logger.info("Mapping for: "+mappingName + " has been loaded.");
		}
	} catch (InputMismatchException | IOException e) {
		logger.error("Error while loading the indexing mappings:", e);
		e.printStackTrace();
	}
}
 
Example #17
Source File: Mapping.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Mapping()
{
	logger = (OssmeterLogger) OssmeterLogger.getLogger("indexing.documentation.mapping");
	String documentType;
	Pattern versionFinder = Pattern.compile("\"mapping_version\"\\s*:\\s*\"([^\"]+)\"");
	mappings=new HashMap<String,MappingStorage>();
	try {
		String[] mappingsToRead = loadFile(dictionnaryName).split("\n");
		
		for(String mappingName : mappingsToRead)
		{
			if(mappingName.isEmpty())
				continue;
			documentType=mappingName.replace("_", ".");
			mappings.put(documentType, loadMapping(mappingName+".json", versionFinder));
			logger.info("Mapping for: "+mappingName + " has been loaded.");
		}
	} catch (InputMismatchException | IOException e) {
		logger.error("Error while loading the indexing mappings:", e);
		e.printStackTrace();
	}
}
 
Example #18
Source File: Mapping.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Mapping()
{
	logger = (OssmeterLogger) OssmeterLogger.getLogger("indexing.bugs.mapping");
	String documentType;
	Pattern versionFinder = Pattern.compile("\"mapping_version\"\\s*:\\s*\"([^\"]+)\"");
	mappings=new HashMap<String,MappingStorage>();
	try {
		String[] mappingsToRead = loadFile(dictionnaryName).split("\n");
		
		for(String mappingName : mappingsToRead)
		{
			if(mappingName.isEmpty())
				continue;
			documentType=mappingName.replace("_", ".");
			mappings.put(documentType, loadMapping(mappingName+".json", versionFinder));
			logger.info("Mapping for: "+mappingName + " has been loaded.");
		}
	} catch (InputMismatchException | IOException e) {
		logger.error("Error while loading the indexing mappings:", e);
		e.printStackTrace();
	}
}
 
Example #19
Source File: SenticNet5Singleton.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private SenticNet5Singleton()
{
	logger = (OssmeterLogger) OssmeterLogger.getLogger("nlp.resources.sentinet5");
	try
	{
		listPos=new ArrayList<String>();
		listNeg=new ArrayList<String>();
		loadFile();
		logger.info("Lexicon has been sucessfully loaded");
	}
	catch (IOException | InputMismatchException  e) 
	{
		logger.error("Error while loading the lexicon:", e);
		e.printStackTrace();
	}		
}
 
Example #20
Source File: MigrationPatternDetectorSingleton.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private void readFile(BufferedReader lexicon) throws IOException, InputMismatchException
{
	String line;
	List<Pattern> patternGroup=new ArrayList<Pattern>();
	
	while((line = lexicon.readLine()) != null)
	{
		if (!line.trim().startsWith("#"))
		{
			patternGroup.add(Pattern.compile("(?i)\\b"+line+"\\b"));
		}
		if (line.trim().startsWith("##") && patternGroup.size()>0)
		{
			patternGroups.add(patternGroup);
			patternGroup=new ArrayList<Pattern>();
		}
		
	}
}
 
Example #21
Source File: Mapping.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Mapping()
{
	logger = (OssmeterLogger) OssmeterLogger.getLogger("indexing.documentation.mapping");
	String documentType;
	Pattern versionFinder = Pattern.compile("\"mapping_version\"\\s*:\\s*\"([^\"]+)\"");
	mappings=new HashMap<String,MappingStorage>();
	try {
		String[] mappingsToRead = loadFile(dictionnaryName).split("\n");
		
		for(String mappingName : mappingsToRead)
		{
			if(mappingName.isEmpty())
				continue;
			documentType=mappingName.replace("_", ".");
			mappings.put(documentType, loadMapping(mappingName+".json", versionFinder));
			logger.info("Mapping for: "+mappingName + " has been loaded.");
		}
	} catch (InputMismatchException | IOException e) {
		logger.error("Error while loading the indexing mappings:", e);
		e.printStackTrace();
	}
}
 
Example #22
Source File: UtilsDataset.java    From apogen with Apache License 2.0 6 votes vote down vote up
public void createDatasets(String f) throws IOException {

		createClustersDir();

		if (f.equals("0")) {
			createDomsRTEDDistancesMatrix();
		} else if (f.equals("1")) {
			createDomsLevenshteinDistancesMatrix();
		} else if (f.equals("2")) {
			createTagsFrequenciesMatrix();
		} else if (f.equals("3")) {
			createUrlsDistancesMatrix();
		} else {
			throw new InputMismatchException("[ERR] UtilsDataset@createDatasets: Unexpected dataset input");
		}
		// createWordsFrequenciesMatrix();
	}
 
Example #23
Source File: ReadingIntegers.java    From java-1-class-demos with MIT License 6 votes vote down vote up
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);
	}
 
Example #24
Source File: Benchmark.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: LowestBasePalindrome.java    From Java with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = 0;
    while (true) {
        try {
            System.out.print("Enter number: ");
            n = in.nextInt();
            break;
        } catch (InputMismatchException e) {
            System.out.println("Invalid input!");
            in.next();
        }
    }
    System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n));
    System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n)));
    in.close();
}
 
Example #26
Source File: InputReader.java    From EasySRL with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #27
Source File: InputReader.java    From EasySRL with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #28
Source File: InputReader.java    From EasySRL with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #29
Source File: StdIn.java    From algs4 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Reads the next token from standard input, parses it as a boolean,
 * and returns the boolean.
 *
 * @return the next boolean on standard input
 * @throws NoSuchElementException if standard input is empty
 * @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:
 *    {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,
 *    ignoring case
 */
public static boolean readBoolean() {
    try {
        String token = readString();
        if ("true".equalsIgnoreCase(token))  return true;
        if ("false".equalsIgnoreCase(token)) return false;
        if ("1".equals(token))               return true;
        if ("0".equals(token))               return false;
        throw new InputMismatchException("attempts to read a 'boolean' value from standard input, "
                                       + "but the next token is \"" + token + "\"");
    }
    catch (NoSuchElementException e) {
        throw new NoSuchElementException("attempts to read a 'boolean' value from standard input, "
                                       + "but no more tokens are available");
    }

}
 
Example #30
Source File: In.java    From algs4 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Reads the next token from this input stream, parses it as a {@code boolean}
 * (interpreting either {@code "true"} or {@code "1"} as {@code true},
 * and either {@code "false"} or {@code "0"} as {@code false}).
 *
 * @return the next {@code boolean} in this input stream
 * @throws NoSuchElementException if the input stream is empty
 * @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}
 */
public boolean readBoolean() {
    try {
        String token = readString();
        if ("true".equalsIgnoreCase(token))  return true;
        if ("false".equalsIgnoreCase(token)) return false;
        if ("1".equals(token))               return true;
        if ("0".equals(token))               return false;
        throw new InputMismatchException("attempts to read a 'boolean' value from the input stream, "
                                       + "but the next token is \"" + token + "\"");
    }
    catch (NoSuchElementException e) {
        throw new NoSuchElementException("attempts to read a 'boolean' value from the input stream, "
                                       + "but no more tokens are available");
    }
}