类java.util.Scanner源码实例Demo

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

源代码1 项目: ctsms   文件: DepartmentManager.java
public void interactiveCreateDepartment() {
	Scanner in = ExecUtil.getScanner();
	try {
		printDepartments();
		System.out.print("enter new department name l10n key:");
		String nameL10nKey = in.nextLine();
		printDepartmentPasswordPolicy();
		String plainDepartmentPassword = readConfirmedPassword(in, "enter department password:", "confirm department password:");
		PasswordPolicy.DEPARTMENT.checkStrength(plainDepartmentPassword);
		createDepartment(nameL10nKey, DEFAULT_DEPARTMENT_VISIBLE, plainDepartmentPassword);
		System.out.println("department created");
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		in.close();
	}
}
 
源代码2 项目: AlgoCS   文件: Stripies_1161.java
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    Byte n = in.nextByte();
    double ans = 0;
    double a[] = new double[n];
    for (int i = 0; i < a.length; i++) {
        a[i] = in.nextInt();
    }
    Arrays.sort(a);
    ans = a[a.length - 1];
    for (int i = a.length - 1; i > 0; i--) {
        ans = Max(ans, a[i - 1]);
    }
    System.out.printf("%.2f", ans);
}
 
源代码3 项目: Algorithms   文件: ModernArt2.java
public static void main(String[] args) throws Exception{
	Scanner scan=new Scanner(new File("art2.in"));
	PrintWriter writer = new PrintWriter(new File("art2.out"));
	
	int n=scan.nextInt();
	int[] paint=new int[n];
	int ans;
	if(n==7){
		ans=2;
	}else{
		ans=6;
	}

	writer.println(ans);
	writer.close();
	
}
 
源代码4 项目: HMMRATAC   文件: ObservationReader.java
private List<?> readVector(Scanner inFile){
	List<ObservationVector> obseq = new ArrayList<ObservationVector>();
	while(inFile.hasNext()){
		String line = inFile.nextLine();
		String[] temp = line.split(",");
		double[] values = new double[temp.length];
		if (!line.contains("mask")){
			for (int i = 0; i < temp.length;i++){
				values[i] = Double.parseDouble(temp[i]);
			}
		}
		ObservationVector o = new ObservationVector(values);
		obseq.add(o);
	}
	return obseq;
}
 
源代码5 项目: Mathematics   文件: Volume.java
public static void main(String[] args){

		System.out.println("________Welcome to Volume Calculation________\n");
		System.out.println("Choose one of the following\n");
		
		Scanner scan = new Scanner(System.in);

		System.out.println("1	Cube    \n" +
				   "2	Cuboid  \n" + 
				   "3	Cylinder\n" + 
				   "4	Sphere  \n" +
				   "5   Pyramid \n");

		int userChoice = scan.nextInt();

		switch(userChoice){
			case 1: cube();     break;
			case 2: cuboid();   break;
			case 3: cylinder(); break;
			case 4: sphere();   break;
			case 5: pyramid(); break;

			default: System.out.println("Invalid Choice! Try Again\n");
		}
		
	}
 
源代码6 项目: OrigamiSMTP   文件: DataHandler.java
/** Processes the data message
 * @param inFromClient The input stream from the client
 */
public void processMessage(Scanner inFromClient)
{
	inFromClient.useDelimiter(""+Constants.CRLF+"."+Constants.CRLF);
	if(inFromClient.hasNext())
	{
		data = inFromClient.next();
		// Clear out buffer
		inFromClient.nextLine();
		inFromClient.nextLine();
		response = "250 OK" + Constants.CRLF;
	}
	else
	{
		response = "501 Syntax Error no lines" + Constants.CRLF;
	}
	
	
}
 
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	Integer[] numbers = new Integer[10];

	// Prompt the user to enter 10 integers
	System.out.print("Enter 10 integers: ");
	for (int i = 0; i < numbers.length; i++)
		numbers[i] = input.nextInt();
	
	// Create Integer BST
	BST<Integer> intTree = new BST<>(numbers);

	// Traverse tree inorder
	System.out.print("Tree inorder: ");
	intTree.inorder();
	System.out.println();
}
 
源代码8 项目: algorithms   文件: AnagramsQuick.java
public List<String> findAnagramsQuickly(String pathToFile, String word) {
    long startTime = System.nanoTime();
    List<String> result = new ArrayList<>();
    try {
        Scanner sc = new Scanner(new File(pathToFile), "Cp1252");
        char[] wordChars = word.toLowerCase().toCharArray();
        Map<Character, Integer> countMap = new HashMap<>();
        for(char character : wordChars) {
            countMap.put(character,countMap.getOrDefault(character, 0) + 1);
        }

        while (sc.hasNextLine()) {
            String curWord = sc.nextLine();
            if (curWord.length() == word.length()) {
                if (isAnagram(curWord, new HashMap<>(countMap))) {
                    result.add(curWord);
                }
            }
        }
    } catch (IOException ioException) {
        throw new RuntimeException(ioException);
    }
    System.out.println("Nano seconds taken:" + (System.nanoTime() - startTime));
    return result;
}
 
源代码9 项目: android-dev-challenge   文件: NetworkUtils.java
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response, null if no response
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        String response = null;
        if (hasInput) {
            response = scanner.next();
        }
        scanner.close();
        return response;
    } finally {
        urlConnection.disconnect();
    }
}
 
public static void main(String[] args) {
    //Input
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    String[] s = new String[n + 2];
    for (int i = 0; i < n; i++) {
        s[i] = sc.next();
    }
    sc.close();

    //Write your code here
    s = Arrays.copyOfRange(s, 0, s.length - 2);
    List<String> input = Arrays.asList(s);
    Arrays.sort(s, (s1, s2) -> {
        int compare = new java.math.BigDecimal(s2).compareTo(new java.math.BigDecimal(s1));
        if (compare == 0) {
            return Integer.compare(input.indexOf(s1), input.indexOf(s2));
        }
        return compare;
    });

    //Output
    for (int i = 0; i < n; i++) {
        System.out.println(s[i]);
    }
}
 
源代码11 项目: mini2Dx   文件: AndroidComponentScanner.java
@Override
public void restoreFrom(Reader reader) throws ClassNotFoundException {
	final Scanner scanner = new Scanner(reader);
	boolean singletons = true;

	scanner.nextLine();
	while (scanner.hasNext()) {
		final String line = scanner.nextLine();
		if(line.startsWith("---")) {
			singletons = false;
		} else if(singletons) {
			singletonClasses.add(Class.forName(line));
		} else {
			prototypeClasses.add(Class.forName(line));
		}
	}
	scanner.close();
}
 
源代码12 项目: StockSimulator   文件: TextClient.java
public void start() {
    Scanner scanner = new Scanner(System.in);
    String nextLine = "";

    do {
        System.out.print("Enter a command (help): ");
        try {
            nextLine = scanner.nextLine();
        } catch (NoSuchElementException e) {
            System.out.println("Goodbye");
            return;
        }
        for (ITextClientSection section:sectionList) {
            if (section.getName().equalsIgnoreCase(nextLine)){
                System.out.println("\n---- Invoking " + section.getName() + " ----");
                section.invoke(nextLine, scanner);
                System.out.println();
            }
        }
    } while (!nextLine.equalsIgnoreCase("quit"));

}
 
public static void main(String[] args) 
{
    Scanner scan = new Scanner( System.in );        
    System.out.println("Heap Sort Test\n");
    int n, i;    
    /* Accept number of elements */
    System.out.println("Enter number of integer elements");
    n = scan.nextInt();    
    /* Make array of n elements */
    int arr[] = new int[ n ];
    /* Accept elements */
    System.out.println("\nEnter "+ n +" integer elements");
    for (i = 0; i < n; i++)
        arr[i] = scan.nextInt();
    /* Call method sort */
    sort(arr);
    /* Print sorted Array */
    System.out.println("\nElements after sorting ");        
    for (i = 0; i < n; i++)
        System.out.print(arr[i]+" ");            
    System.out.println();            
}
 
源代码14 项目: tutorials   文件: RunAlgorithm.java
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
	Scanner in = new Scanner(System.in);
	System.out.println("Run algorithm:");
	System.out.println("1 - Simulated Annealing");
	System.out.println("2 - Simple Genetic Algorithm");
	System.out.println("3 - Ant Colony");
	int decision = in.nextInt();
	switch (decision) {
	case 1:
		System.out.println(
				"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
		break;
	case 2:
		SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
		ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
		break;
	case 3:
		AntColonyOptimization antColony = new AntColonyOptimization(21);
		antColony.startAntOptimization();
		break;
	default:
		System.out.println("Unknown option");
		break;
	}
	in.close();
}
 
源代码15 项目: JavaMainRepo   文件: Twist1.java
public static void main (String[] args){
	int i,s=0,nr;
	String nr1; 
	Scanner in = new Scanner (System.in);
	nr1 = in.nextLine();
	in.close();
	try{
		nr= Integer.parseInt(nr1);
		System.out.println("The limit number is " + nr);
		for(i=2;i<nr;i++){
			if((i%3==0) || (i%5==0))
				s=s+i;
		}
	}
	catch(NumberFormatException nx){
		System.out.println("Enter valid number ");
	}
	
	System.out.println("Sum is " + s);
		
}
 
源代码16 项目: JavaSteam   文件: SampleSteamGuardRememberMe.java
private void onConnected(ConnectedCallback callback) {
    System.out.println("Connected to Steam! Logging in " + user + "...");

    LogOnDetails details = new LogOnDetails();
    details.setUsername(user);

    File loginKeyFile = new File("loginkey.txt");
    if (loginKeyFile.exists()) {
        try (Scanner s = new Scanner(loginKeyFile)) {
            details.setLoginKey(s.nextLine());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        details.setPassword(pass);
    }

    details.setTwoFactorCode(twoFactorAuth);
    details.setAuthCode(authCode);
    details.setShouldRememberPassword(true);

    steamUser.logOn(details);
}
 
源代码17 项目: Intro-to-Java-Programming   文件: Exercise_03_23.java
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	// Prompt the user to enter a point (x, y)
	System.out.print("Enter a point with two coordinates: ");
	double x = input.nextDouble();
	double y = input.nextDouble();

	// Check whether the point is within the rectangle
	// centered at (0, 0) with width 10 and height 5
	boolean withinRectangle = (Math.pow(Math.pow(x, 2), 0.5) <= 10 / 2 ) ||
									  (Math.pow(Math.pow(y, 2), 0.5) <= 5.0 / 2);

	// Display results
	System.out.println("Point (" + x + ", " + y + ") is " +
		((withinRectangle) ? "in " : "not in ") + "the rectangle");
}
 
源代码18 项目: Beats   文件: DataParserDWI.java
private static void parseStop(DataFile df, String buffer) throws DataParserException {
	Scanner vsc = new Scanner(buffer);
	vsc.useDelimiter(",");
	while (vsc.hasNext()) {
		String pair = vsc.next().trim();
		try {
			if (pair.indexOf('=') < 0) {
				throw new Exception("No '=' found");
			} else {
				float beat = Float.parseFloat(pair.substring(0, pair.indexOf('='))) / 4f;
				float value = Float.parseFloat(pair.substring(pair.indexOf('=') + 1)) / 1000f;
				df.addStop(beat, value);
			}
		} catch (Exception e) { // Also catch NumberFormatExceptions
			vsc.close();
			throw new DataParserException(
					e.getClass().getSimpleName(),
					"Improperly formatted #FREEZE pair \"" + pair + "\": " +
					e.getMessage(), e
					);
		}
	}
	vsc.close();
}
 
源代码19 项目: jdk8u_jdk   文件: TzdbZoneRulesCompiler.java
/**
 * Parses a Rule line.
 *
 * @param s  the line scanner, not null
 */
private void parseRuleLine(Scanner s) {
    TZDBRule rule = new TZDBRule();
    String name = s.next();
    if (rules.containsKey(name) == false) {
        rules.put(name, new ArrayList<TZDBRule>());
    }
    rules.get(name).add(rule);
    rule.startYear = parseYear(s, 0);
    rule.endYear = parseYear(s, rule.startYear);
    if (rule.startYear > rule.endYear) {
        throw new IllegalArgumentException("Year order invalid: " + rule.startYear + " > " + rule.endYear);
    }
    parseOptional(s.next());  // type is unused
    parseMonthDayTime(s, rule);
    rule.savingsAmount = parsePeriod(s.next());
    rule.text = parseOptional(s.next());
}
 
源代码20 项目: jdk8u-dev-jdk   文件: ProbeIB.java
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
源代码21 项目: JavaRushTasks   文件: Solution.java
public static void main(String[] args) throws Exception {
    //напишите тут ваш код

    int[] vect = new int[15];
    Scanner sc = new Scanner(System.in);

    for (int i=0;i<vect.length;i++) {
        vect[i] = Integer.parseInt(sc.nextLine());
    }


    int even_sum = 0;
    int odd_sum = 0;
    for (int i=0;i<vect.length;i++) {
        if ((i % 2) ==0)
            even_sum += vect[i];
        else
            odd_sum += vect[i];
    }

    if (even_sum>odd_sum)
        System.out.println("В домах с четными номерами проживает больше жителей.");
    else
        System.out.println("В домах с нечетными номерами проживает больше жителей.");
}
 
源代码22 项目: jumbune   文件: ExecutionUtil.java
/**
 * This method will return true if user enters Yes and will return false if user enters No or simply presses Enter key i.e. leaves blank answer
 * 
 * @param reader
 * @param validMessage
 * @param question
 *            TODO
 * @return
 * @throws JumbuneException
 */
public static boolean askYesNoInfo(Scanner scanner, String validMessage, String question) {
	YesNo yesNo;
	askQuestion(question);
	while (true) {
		try {
			String input;

			input = readFromReader(scanner);

			if (input.length() == 0) {
				return false;
			}
			yesNo = YesNo.valueOf(input.toUpperCase());
			break;
		} catch (IllegalArgumentException ilEx) {
			CONSOLE_LOGGER.error(validMessage);
		}
	}

	if (YesNo.YES.equals(yesNo) || YesNo.Y.equals(yesNo)) {
		return true;
	}
	return false;
}
 
源代码23 项目: openjdk-jdk9   文件: XPreferTest.java
Dir getChosenOrigin(String compilerOutput) {
    Scanner s = new Scanner(compilerOutput);
    while (s.hasNextLine()) {
        String line = s.nextLine();
        if (line.matches("\\[loading .*\\]")) {
            for (Dir dir : Dir.values()) {
                // On Windows all paths are printed with '/' except
                // paths inside zip-files, which are printed with '\'.
                // For this reason we accept both '/' and '\' below.
                String regex = dir.file.getName() + "[\\\\/]" + classId;
                if (Pattern.compile(regex).matcher(line).find())
                    return dir;
            }
        }
    }
    return null;
}
 
源代码24 项目: UVA   文件: 10714 Ants.java
public static void main (String [] args) throws Exception {
	Scanner sc=new Scanner(System.in);
	int testCaseCount=sc.nextInt();
	for (int testCase=0;testCase<testCaseCount;testCase++) {
		int L=sc.nextInt();
		int N=sc.nextInt();
		
		int [] ants=new int[N];
		for (int n=0;n<N;n++) ants[n]=sc.nextInt();
		Arrays.sort(ants);
		
		int shortest=Integer.MIN_VALUE;
		for (int n=0;n<N;n++) {
			int left=ants[n];
			int right=L-ants[n];
			shortest=Math.max(shortest, Math.min(left, right));
		}
		int longest=Math.max(L-ants[0], ants[ants.length-1]);
		
		System.out.printf("%d %d\n",shortest,longest);
	}
}
 
源代码25 项目: jelectrum   文件: PeerManager.java
private void addSelfToPeer(PrintStream out, Scanner scan)
  throws org.json.JSONException
{ 
  JSONArray peersToAdd = new JSONArray();
  peersToAdd.put(getServerFeatures());
  
  JSONObject request = new JSONObject();
  request.put("id","add_peer");
  request.put("method", "server.add_peer");
  request.put("params", peersToAdd);

  out.println(request.toString(0));
  out.flush();

  //JSONObject reply = new JSONObject(scan.nextLine());
  //jelly.getEventLog().log(reply.toString());


}
 
源代码26 项目: tac   文件: Utils.java
public static List <Pair<String, String>> parse (final URI uri, final String encoding) {
    List <Pair<String, String>> result = new ArrayList<Pair<String, String>>();
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        parse(result, new Scanner(query), encoding);
    }
    return result;
}
 
源代码27 项目: JavaExercises   文件: User.java
User(Elevator elevator) {
    this.elevator = elevator;
    reader = new Scanner(System.in);
    isOutside = true;
    isOver = false;
    floor = 1;
    console();
}
 
源代码28 项目: iBioSim   文件: ZoneTest.java
/**
 * Reads in zones for testing.
 * @param zoneFile
 * 			The file containing the test zones.
 * @return
 * 			An array of zones for testing.
 * 			
 */
@SuppressWarnings("unused")
private static ZoneType[] readTestZones(File zoneFile)
{
	try {
		Scanner read = new Scanner(zoneFile);
		
		while(read.hasNextLine())
		{
			String line = read.nextLine();
			line.trim();
			
			if(line.equals("start"))
			{
				
			}
		}
		
		read.close();
		
	} catch (FileNotFoundException e) {
		e.printStackTrace();
		System.err.print("File not found.");
	}
	
	
	return null;
}
 
源代码29 项目: Java-Data-Analysis   文件: Example1.java
public static void map(String filename, PrintWriter writer) 
        throws IOException {
    Scanner input = new Scanner(new File(filename));
    input.useDelimiter("[.,:;()?!\"\\s]+");
    while (input.hasNext()) {
        String word = input.next();
        writer.printf("%s 1%n", word.toLowerCase());
    }
    input.close();
}
 
源代码30 项目: graphicsfuzz   文件: PersistentData.java
public long getJobId() {
  String str = readKeyFile(com.graphicsfuzz.glesworker.Constants.PERSISTENT_KEY_JOB_ID);
  Scanner scan = new Scanner(str);
  if (scan.hasNextLong()) {
    return scan.nextLong();
  } else {
    return -1L;
  }
}
 
 类所在包
 同包方法