类java.util.InputMismatchException源码实例Demo

下面列出了怎么用java.util.InputMismatchException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: fido2   文件: TPMECCUnique.java
public static TPMECCUnique unmarshal(byte[] bytes){
    int pos = 0;
    short xSize = Marshal.stream16ToShort(Arrays.copyOfRange(bytes, pos, pos+TPMConstants.SIZEOFSHORT));
    pos += TPMConstants.SIZEOFSHORT;
    TPM2B x = new TPM2B(Arrays.copyOfRange(bytes, pos, pos+xSize));
    pos += xSize;

    short ySize = Marshal.stream16ToShort(Arrays.copyOfRange(bytes, pos, pos+TPMConstants.SIZEOFSHORT));
    pos += TPMConstants.SIZEOFSHORT;
    TPM2B y = new TPM2B(Arrays.copyOfRange(bytes, pos, pos+ySize));
    pos += ySize;

    if(pos != bytes.length){
        throw new InputMismatchException("TPMCertifyInfo failed to unmarshal");
    }

    return new TPMECCUnique(x, y);
}
 
源代码2 项目: fido2   文件: TPMCertifyInfo.java
public static TPMCertifyInfo unmarshal(byte[] bytes){
    int pos = 0;
    int sizeOfName = Marshal.stream16ToShort(Arrays.copyOfRange(bytes, pos, pos+TPMConstants.SIZEOFSHORT));
    pos += TPMConstants.SIZEOFSHORT;
    TPM2B name = new TPM2B(Arrays.copyOfRange(bytes, pos, pos+sizeOfName));
    pos += sizeOfName;
    int sizeOfQualifiedName = Marshal.stream16ToShort(Arrays.copyOfRange(bytes, pos, pos + TPMConstants.SIZEOFSHORT));
    pos += TPMConstants.SIZEOFSHORT;
    TPM2B qualifiedName = new TPM2B(Arrays.copyOfRange(bytes, pos, pos + sizeOfQualifiedName));
    pos += sizeOfQualifiedName;

    if(pos != bytes.length){
        throw new InputMismatchException("TPMCertifyInfo failed to unmarshal");
    }

    return new TPMCertifyInfo(name, qualifiedName);
}
 
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++];
}
 
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;
}
 
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++];
}
 
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;
}
 
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;
}
 
源代码8 项目: JYTB   文件: App.java
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;
        }
    }
}
 
源代码9 项目: chart-fx   文件: DataSetSerialiser.java
protected static Optional<FieldHeader> checkFieldCompatibility(final IoBuffer buffer,
        final List<FieldHeader> fieldHeaderList, final String fieldName, final DataType... requireDataTypes) {
    Optional<FieldHeader> fieldHeader = FieldHeader.findHeaderFor(fieldHeaderList, fieldName);
    if (!fieldHeader.isPresent()) {
        return Optional.empty();
    }

    if (fieldHeader.get().getFieldName().equals(fieldName)) {
        boolean foundMatchingDataType = false;
        for (DataType dataType : requireDataTypes) {
            if (fieldHeader.get().getDataType().equals(dataType)) {
                foundMatchingDataType = true;
                break;
            }
        }
        if (!foundMatchingDataType) {
            throw new InputMismatchException(fieldName + " is type " + fieldHeader.get().getDataType()
                                             + " vs. required type " + Arrays.asList(requireDataTypes).toString());
        }

        final long dataPosition = fieldHeader.get().getDataBufferPosition();
        buffer.position(dataPosition);
        return fieldHeader;
    }
    return Optional.empty();
}
 
源代码10 项目: Mathematics   文件: DecimalToBinaryConversion.java
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]);
   }
   
 }
 
源代码11 项目: Mathematics   文件: Factorial.java
public static void main(String[] args){
    try{
        Scanner scan = new Scanner (System.in);
    
    //Prompt user for a number to calculte its factorial number
    System.out.println("Insert a positive integer number: ");
    int num = scan.nextInt();
    if(num<0)throw(new InputMismatchException());
    long F=facto(num);
        System.out.println("Factorial number of "+num+" is " +F);
    }
    catch (InputMismatchException ex){
      System.err.println("Please provide a positive integer number (no text, real or negative number). Restart the program and try again!");
      main(new String[0]);
    }
}
 
源代码12 项目: Mathematics   文件: fibonacci.java
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]);
    }
}
 
源代码13 项目: Mathematics   文件: SpecialTriangles.java
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]);
    }
}
 
源代码14 项目: Mathematics   文件: logarithms.java
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]);
    }


}
 
源代码15 项目: Mathematics   文件: lcm.java
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]);
    }
}
 
源代码16 项目: public   文件: TextView.java
@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);
    }
  }
}
 
源代码17 项目: public   文件: TextView.java
@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);
    }
  }
}
 
源代码18 项目: scava   文件: Mapping.java
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();
	}
}
 
源代码19 项目: scava   文件: DocumentationClassifierSingleton.java
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();
	}
}
 
源代码20 项目: scava   文件: FileParserSingleton.java
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]);
		}
	}
}
 
源代码21 项目: scava   文件: Mapping.java
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();
	}
}
 
源代码22 项目: scava   文件: Mapping.java
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();
	}
}
 
源代码23 项目: scava   文件: SenticNet5Singleton.java
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();
	}		
}
 
源代码24 项目: scava   文件: MigrationPatternDetectorSingleton.java
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>();
		}
		
	}
}
 
源代码25 项目: scava   文件: Mapping.java
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();
	}
}
 
源代码26 项目: apogen   文件: UtilsDataset.java
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] [email protected]: Unexpected dataset input");
		}
		// createWordsFrequenciesMatrix();
	}
 
源代码27 项目: java-1-class-demos   文件: ReadingIntegers.java
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);
	}
 
源代码28 项目: document-management-system   文件: Benchmark.java
/**
 * 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;
}
 
源代码29 项目: Java   文件: LowestBasePalindrome.java
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();
}
 
源代码30 项目: EasySRL   文件: InputReader.java
@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);
}
 
 类所在包
 同包方法