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

The following examples show how to use java.util.Scanner#hasNextInt() . 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: Main.java    From Particle-Swarm-Optimization with MIT License 6 votes vote down vote up
private static int getUserInt (String msg) {
    int input;
    while (true) {
        Scanner sc = new Scanner(System.in);
        System.out.print(msg);

        if (sc.hasNextInt()) {
            input = sc.nextInt();

            if (input <= 0) {
                System.out.println("Number must be positive.");
            } else {
                break;
            }

        } else {
            System.out.println("Invalid input.");
        }
    }
    return input;
}
 
Example 2
Source File: PyroSerializer.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static int compareLibraryVersions(String actual, String other) {
	Scanner s1 = new Scanner(actual);
	Scanner s2 = new Scanner(other);
	s1.useDelimiter("\\.");
	s2.useDelimiter("\\.");

	while(s1.hasNextInt() && s2.hasNextInt()) {
	    int v1 = s1.nextInt();
	    int v2 = s2.nextInt();
	    if(v1 < v2) {
	    	s1.close();
	    	s2.close();
	        return -1;
	    } else if(v1 > v2) {
	    	s1.close();
	    	s2.close();
	        return 1;
	    }
	}

	int result = 0;
	if(s1.hasNextInt()) result=1; //str1 has an additional lower-level version number
	s1.close();
	s2.close();
	return result;
}
 
Example 3
Source File: AlgorithmsWeekThreeTest.java    From algorithms with MIT License 6 votes vote down vote up
@Test
public void main() throws FileNotFoundException {
    Scanner sc1 = new Scanner(new File("src/main/resources/knapsack1.txt"));
    int capacity1 = sc1.nextInt();
    List<KnapsackItem> items1 = new ArrayList<KnapsackItem>(sc1.nextInt());
    while (sc1.hasNextInt()) {
        items1.add(new KnapsackItem(sc1.nextInt(), sc1.nextInt()));
    }
    sc1.close();
    KnapsackProblem knapsackProblem1 = new KnapsackProblem(capacity1, items1);
    assertThat(knapsackProblem1.getMaxValue()).isEqualTo(2493893);

    Scanner sc2 = new Scanner(new File("src/main/resources/knapsack_big.txt"));
    int capacity2 = sc2.nextInt();
    List<KnapsackItem> items2 = new ArrayList<KnapsackItem>(sc2.nextInt());
    while (sc2.hasNextInt()) {
        items2.add(new KnapsackItem(sc2.nextInt(), sc2.nextInt()));
    }
    sc2.close();
    KnapsackProblem knapsackProblem2 = new KnapsackProblem(capacity2, items2);
    assertThat(knapsackProblem2.getMaxValue()).isEqualTo(4243395);
}
 
Example 4
Source File: Solitaire.java    From CS112-Rutgers with MIT License 6 votes vote down vote up
/**
 * Makes a circular linked list deck out of values read from scanner.
 */
public void makeDeck(Scanner scanner) throws IOException {
   CardNode cn = null;
   if (scanner.hasNextInt()) {
      cn = new CardNode();
      cn.cardValue = scanner.nextInt();
      cn.next = cn;
      deckRear = cn;
   }
   while (scanner.hasNextInt()) {
      cn = new CardNode();
      cn.cardValue = scanner.nextInt();
      cn.next = deckRear.next;
      deckRear.next = cn;
      deckRear = cn;
   }
}
 
Example 5
Source File: AlgorithmsWeekSixTest.java    From algorithms with MIT License 5 votes vote down vote up
@Test
public void main() throws FileNotFoundException {
    //isSCC = true;
    for (int i = 1; i < 7; i++) {
        Scanner sc = new Scanner(new File("src/main/resources/2sat" + i + ".txt"));
        int variableCount = sc.nextInt();
        OrderedGraph orderedGraph = new OrderedGraph(variableCount * 2);
        while (sc.hasNextInt()) {
            int firstVar = convert(sc.nextInt(), variableCount);
            int secondVar = convert(sc.nextInt(), variableCount);
            orderedGraph.addEdge(not(firstVar, variableCount), secondVar);
            orderedGraph.addEdge(not(secondVar, variableCount), firstVar);
        }
        sc.close();
        Scc2SAT ssc2SAT = new Scc2SAT(orderedGraph);
        System.out.println("Result = " + ssc2SAT.getResult());
        System.out.println("4 and 5 connected = " + ssc2SAT.connected(4, 5));
        System.out.println("Solution = " + ssc2SAT.getSolution());
        System.out.println("GroupNumber 6 = " + ssc2SAT.groupNumber(6));
    }
    //  isPapadimitrou
    /*for (int i = 1; i < 7; i++) {
        Scanner sc = new Scanner(new File("src/main/resources/2sat" + i + ".txt"));
        int variableCount = sc.nextInt();
        int[][] clauses = new int[variableCount][2];
        int index = 0;
        while (sc.hasNextInt()) {
            clauses[index][0] = sc.nextInt();
            clauses[index][1] = sc.nextInt();
            index++;
        }
        sc.close();
        Papadimitrou papadimitrou = new Papadimitrou(clauses);
        System.out.println(papadimitrou.getResult());
    }*/
}
 
Example 6
Source File: Main.java    From Particle-Swarm-Optimization with MIT License 5 votes vote down vote up
private static Particle.FunctionType getFunction () {
    Particle.FunctionType function = null;
    do {
        Scanner sc = new Scanner(System.in);
        printMenu();

        if (sc.hasNextInt()) {
            function = getFunction(sc.nextInt());
        } else {
            System.out.println("Invalid input.");
        }

    } while (function == null);
    return function;
}
 
Example 7
Source File: PinocchioGadget.java    From jsnark with MIT License 5 votes vote down vote up
private ArrayList<Integer> getOutputs(String line) {
	Scanner scanner = new Scanner(line.substring(line.lastIndexOf("<") + 1, line.lastIndexOf(">")));
	ArrayList<Integer> outs = new ArrayList<>();
	while (scanner.hasNextInt()) {
		int v = scanner.nextInt();
		outs.add(v);
	}
	scanner.close();
	return outs;
}
 
Example 8
Source File: ScannerDemo.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in); // 从键盘接收数据
    int i = 0;
    float f = 0.0f;
    System.out.print("输入整数:");
    if (scan.hasNextInt()) { // 判断输入的是否是整数
        i = scan.nextInt(); // 接收整数
        System.out.println("整数数据:" + i);
    } else {
        System.out.println("输入的不是整数!");
    }

    System.out.print("输入小数:");
    if (scan.hasNextFloat()) { // 判断输入的是否是小数
        f = scan.nextFloat(); // 接收小数
        System.out.println("小数数据:" + f);
    } else {
        System.out.println("输入的不是小数!");
    }

    Date date = null;
    String str = null;
    System.out.print("输入日期(yyyy-MM-dd):");
    if (scan.hasNext("^\\d{4}-\\d{2}-\\d{2}$")) { // 判断
        str = scan.next("^\\d{4}-\\d{2}-\\d{2}$"); // 接收
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
        } catch (Exception e) {
        }
    } else {
        System.out.println("输入的日期格式错误!");
    }
    System.out.println(date);
}
 
Example 9
Source File: Java Exception Handling.java    From HackerRank-Solutions with The Unlicense 5 votes vote down vote up
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    while (in .hasNextInt()) {
        int n = in .nextInt();
        int p = in .nextInt();
        MyCalculator my_calculator = new MyCalculator();
        try {
            System.out.println(my_calculator.power(n, p));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
 
Example 10
Source File: JavaScannerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenValidateInputUsingScanner_thenValidated() throws IOException {
    final String input = "2000";
    final InputStream stdin = System.in;
    System.setIn(new ByteArrayInputStream(input.getBytes()));

    final Scanner scanner = new Scanner(System.in);

    final boolean isIntInput = scanner.hasNextInt();
    assertTrue(isIntInput);

    System.setIn(stdin);
    scanner.close();
}
 
Example 11
Source File: SSDeepHashMatcher.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidHash(String inputHash) {
    // format looks like
    // blocksize:hash:hash

    String [] fields = inputHash.split(":", 3);

    if (fields.length == 3) {
        Scanner sc = new Scanner(fields[0]);

        boolean isNumber = sc.hasNextInt();
        if (isNumber == false && logger != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Field should be numeric but got '{}'. Will tell processor to ignore.",
                        new Object[] {fields[0]});
            }
        }

        boolean hashOneIsNotEmpty = !fields[1].isEmpty();
        boolean hashTwoIsNotEmpty = !fields[2].isEmpty();

        if (isNumber && hashOneIsNotEmpty && hashTwoIsNotEmpty) {
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: Main.java    From algorithm-primer with MIT License 5 votes vote down vote up
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int[] prices = null;
    if (sc.hasNextInt()){
        int len = sc.nextInt();
        prices = new int[len];
    }

    for (int i = 0; i < prices.length; ){
        if (sc.hasNextInt()){
            prices[i++] = sc.nextInt();
        }
    }

    java.util.Arrays.sort(prices);
    int price = prices[0];
    int rank = 1;
    for (int i = 1; i < prices.length; i ++){
        if (prices[i] != price){
            rank ++;
            price = prices[i];
            if (rank == 3) break;
        }
    }
    if (rank != 3) price = -1;
    System.out.println(price);
}
 
Example 13
Source File: Client.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param portStr port number as a String value
 * @return Redis port number
 */
protected static int getPortNumber(String portStr) {
    Scanner s = new Scanner(portStr);
    int port;
    if (!s.hasNextInt() || (port = s.nextInt()) < 0 || s.hasNext()) {
        throw new StoreException("Invalid Redis port: " + portStr);
    }
    return port;
}
 
Example 14
Source File: NumberUtils.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parse a string value into an integer. If the string value
 * is null or is not an integer, returns a default value.
 * This method will never throw and returns the wrapper type.
 *
 * @param str string to parse
 * @param def default integer value
 * @return parsed integer
 */
public static Integer parseInt(String str, Integer def) {
    if (str == null) {
        return def;
    }
    Scanner scnr = new Scanner(str);
    if (!scnr.hasNextInt()) {
        return def;
    }
    return scnr.nextInt();
}
 
Example 15
Source File: Node.java    From dexter with Apache License 2.0 5 votes vote down vote up
public Node decode(String record) {
	Scanner sc = new Scanner(record).useDelimiter("[\t ]");
	int node = sc.nextInt();
	List<Integer> neighbours = new LinkedList<Integer>();
	while (sc.hasNextInt()) {
		neighbours.add(sc.nextInt());
	}
	int size = neighbours.size();
	int[] ngh = new int[size];
	for (int i = 0; i < size; i++) {
		ngh[i] = neighbours.get(i);
	}

	return new Node(node, ngh);
}
 
Example 16
Source File: MountainsAndFlame.java    From Project with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 输入两部分值:数组长度和数组具体的内容
    Scanner in = new Scanner(System.in);
    while (in.hasNextInt()) {
        int size = in.nextInt();
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = in.nextInt();
        }
        System.out.println(communications(arr));
    }
    in.close();
}
 
Example 17
Source File: 00338 SameGame Simulation.java    From UVA with GNU General Public License v3.0 4 votes vote down vote up
public static void main (String [] args) throws Exception {
	Scanner sc=new Scanner(System.in);
	int testCase=1;
	while (sc.hasNextInt()) {
		int X=sc.nextInt(), Y=sc.nextInt();
		if (X==0 && Y==0) break;
		
		int [][] num=new int [X][Y];
		for (int x=0;x<X;x++) for (int y=0;y<Y;y++) num[X-x-1][y]=sc.nextInt();
		
		ArrayList<int []> selections=new ArrayList<>();
		while (true) {
			int sx=sc.nextInt(), sy=sc.nextInt();
			if (sx==0 && sy==0) break;
			selections.add(new int [] {X-sx,sy-1});
		}
		
		int remaining=X*Y;
		for (int [] selection : selections) {
			int x=selection[0], y=selection[1];
		 	if (x>=0 && x<X && y>=0 && y<Y && num[selection[0]][selection[1]]>=0) {
				boolean canRemove=false;
				for (int [] delta : Deltas) {
					int dx=x+delta[0], dy=y+delta[1];
					if (dx>=0 && dx<X && dy>=0 && dy<Y) canRemove|=num[x][y]==num[dx][dy];
				}
				if (canRemove) {
					remaining-=removeNum(num,x,y,num[x][y]);
					num[x][y]=-1;
					remaining+=1;
					if (remaining>0) {
						moveDown(num);
						moveLeft(num);
					}
				}
		 	}
		}
		
		if (testCase>1) System.out.println();
		StringBuilder sb=new StringBuilder();
		sb.append("Grid ");
		sb.append(testCase);
		sb.append(".\n");
		if (remaining==0) sb.append("    Game Won\n");
		else {
			for (int x=0;x<X;x++) {
				sb.append("    ");
				for (int y=0;y<Y;y++) {
					sb.append((num[x][y]>=0) ? String.valueOf(num[x][y]) : " ");
					sb.append(' ');
				}
				sb.setCharAt(sb.length()-1, '\n');
			}
		}
		System.out.print(sb.toString());
		testCase++;
	}
	
}
 
Example 18
Source File: AvroRecordConverter.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Converts the data from one schema to another. If the types are the same,
 * no change will be made, but simple conversions will be attempted for
 * other types.
 *
 * @param content
 *            The data to convert, generally taken from a field in an input
 *            Record.
 * @param inputSchema
 *            The schema of the content object
 * @param outputSchema
 *            The schema to convert to.
 * @return The content object, converted to the output schema.
 * @throws AvroConversionException
 *             When conversion is impossible, either because the output type
 *             is not supported or because numeric data failed to parse.
 */
private Object convertData(Object content, Schema inputSchema,
        Schema outputSchema) throws AvroConversionException {
    if (content == null) {
        // No conversion can happen here.
        if (supportsNull(outputSchema)) {
            return null;
        }
        throw new AvroConversionException("Output schema " + outputSchema
                + " does not support null");
    }

    Schema nonNillInput = getNonNullSchema(inputSchema);
    Schema nonNillOutput = getNonNullSchema(outputSchema);
    if (nonNillInput.getType().equals(nonNillOutput.getType())) {
        return content;
    } else {
        if (nonNillOutput.getType() == Schema.Type.STRING) {
            return content.toString();
        }

        // For the non-string cases of these, we will try to convert through
        // string using Scanner to validate types. This means we could
        // return questionable results when a String starts with a number
        // but then contains other content
        Scanner scanner = new Scanner(content.toString());
        scanner.useLocale(locale);
        switch (nonNillOutput.getType()) {
        case LONG:
            if (scanner.hasNextLong()) {
                return scanner.nextLong();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to long");
            }
        case INT:
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to int");
            }
        case DOUBLE:
            if (scanner.hasNextDouble()) {
                return scanner.nextDouble();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to double");
            }
        case FLOAT:
            if (scanner.hasNextFloat()) {
                return scanner.nextFloat();
            } else {
                throw new AvroConversionException("Cannot convert "
                        + content + " to float");
            }
        default:
            throw new AvroConversionException("Cannot convert to type "
                    + nonNillOutput.getType());
        }
    }
}
 
Example 19
Source File: ProcessInformations.java    From javamelody with Apache License 2.0 4 votes vote down vote up
private ProcessInformations(Scanner sc, boolean windows, boolean macOrAix) {
	super();
	if (windows) {
		final StringBuilder imageNameBuilder = new StringBuilder(sc.next());
		while (!sc.hasNextInt()) {
			imageNameBuilder.append(' ').append(sc.next());
		}
		pid = sc.nextInt();
		if ("Console".equals(sc.next())) {
			// ce if est nécessaire si windows server 2003 mais sans connexion à distance ouverte
			// (comme tasklist.txt dans resources de test,
			// car parfois "Console" est présent mais parfois non)
			sc.next();
		}
		final String memory = sc.next();
		cpuPercentage = -1;
		memPercentage = -1;
		vsz = Integer.parseInt(memory.replace(".", "").replace(",", "").replace("ÿ", ""));
		rss = -1;
		tty = null;
		sc.next();
		sc.skip(WINDOWS_STATE_PATTERN);
		stat = null;
		final StringBuilder userBuilder = new StringBuilder(sc.next());
		while (!sc.hasNext(WINDOWS_CPU_TIME_PATTERN)) {
			userBuilder.append(' ').append(sc.next());
		}
		this.user = userBuilder.toString();
		start = null;
		cpuTime = sc.next();
		command = imageNameBuilder.append("   (").append(sc.nextLine().trim()).append(')')
				.toString();
	} else {
		user = sc.next();
		pid = sc.nextInt();
		cpuPercentage = Float.parseFloat(sc.next().replace(",", "."));
		memPercentage = Float.parseFloat(sc.next().replace(",", "."));
		vsz = sc.nextInt();
		rss = sc.nextInt();
		tty = sc.next();
		stat = sc.next();
		if (macOrAix && sc.hasNextInt()) {
			start = sc.next() + ' ' + sc.next();
		} else {
			start = sc.next();
		}
		cpuTime = sc.next();
		command = sc.nextLine();
	}
}
 
Example 20
Source File: IO.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
public static List<Integer> readListIntger(File fiTxt) throws IOException {
	
	Scanner scanner = new Scanner(fiTxt);
	
    List<Integer> li = new ArrayList<Integer>();
    
    while (scanner.hasNextInt()) {
        li.add(scanner.nextInt());
    }
    
    scanner.close();
    
    return li;
}