Java Code Examples for java.util.Scanner

The following examples show how to use java.util.Scanner. These examples are extracted from open source projects. 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 Project: algorithms   Source File: AnagramsQuick.java    License: MIT License 7 votes vote down vote up
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;
}
 
Example 2
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();
	}
}
 
Example 3
Source Project: AlgoCS   Source File: Stripies_1161.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 4
Source Project: Algorithms   Source File: ModernArt2.java    License: MIT License 6 votes vote down vote up
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();
	
}
 
Example 5
Source Project: HMMRATAC   Source File: ObservationReader.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 6
Source Project: Mathematics   Source File: Volume.java    License: MIT License 6 votes vote down vote up
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");
		}
		
	}
 
Example 7
Source Project: OrigamiSMTP   Source File: DataHandler.java    License: MIT License 6 votes vote down vote up
/** 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;
	}
	
	
}
 
Example 8
Source Project: Intro-to-Java-Programming   Source File: Exercise_25_03.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example 9
Source Project: android-dev-challenge   Source File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 10
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]);
    }
}
 
Example 11
Source Project: mini2Dx   Source File: AndroidComponentScanner.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 12
Source Project: StockSimulator   Source File: TextClient.java    License: GNU General Public License v2.0 6 votes vote down vote up
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"));

}
 
Example 13
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();            
}
 
Example 14
Source Project: tutorials   Source File: RunAlgorithm.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example 15
Source Project: JavaMainRepo   Source File: Twist1.java    License: Apache License 2.0 6 votes vote down vote up
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);
		
}
 
Example 16
Source Project: JavaSteam   Source File: SampleSteamGuardRememberMe.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 17
Source Project: Intro-to-Java-Programming   Source File: Exercise_03_23.java    License: MIT License 6 votes vote down vote up
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");
}
 
Example 18
Source Project: Beats   Source File: DataParserDWI.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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();
}
 
Example 19
/**
 * 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());
}
 
Example 20
Source Project: jdk8u-dev-jdk   Source File: ProbeIB.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example 21
Source Project: JavaRushTasks   Source File: Solution.java    License: MIT License 6 votes vote down vote up
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("В домах с нечетными номерами проживает больше жителей.");
}
 
Example 22
Source Project: jumbune   Source File: ExecutionUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 23
Source Project: openjdk-jdk9   Source File: XPreferTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 24
Source Project: UVA   Source File: 10714 Ants.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
Example 25
Source Project: jelectrum   Source File: PeerManager.java    License: MIT License 6 votes vote down vote up
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());


}
 
Example 26
Source Project: tac   Source File: Utils.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 27
Source Project: JavaExercises   Source File: User.java    License: GNU General Public License v2.0 5 votes vote down vote up
User(Elevator elevator) {
    this.elevator = elevator;
    reader = new Scanner(System.in);
    isOutside = true;
    isOver = false;
    floor = 1;
    console();
}
 
Example 28
Source Project: iBioSim   Source File: ZoneTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Source Project: Java-Data-Analysis   Source File: Example1.java    License: MIT License 5 votes vote down vote up
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();
}
 
Example 30
Source Project: graphicsfuzz   Source File: PersistentData.java    License: Apache License 2.0 5 votes vote down vote up
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;
  }
}