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

The following examples show how to use java.util.Scanner#close() . 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: KSAbstract.java    From OSPREY3 with GNU General Public License v2.0 6 votes vote down vote up
public static ArrayList<String> file2List( String path ) {
	ArrayList<String> ans = new ArrayList<String>();

	try {
		if( !new File(path).exists() ) return ans;

		Scanner s = new Scanner(new File(path));
		while (s.hasNextLine()) ans.add(s.nextLine());
		s.close();

	} catch (Exception ex) {
		throw new Error("can't scan file", ex);
	}

	return ans;
}
 
Example 2
Source File: AndroidLocalFileParser.java    From RESTMock with Apache License 2.0 6 votes vote down vote up
@Override
public String readJsonFile(String jsonFilePath) throws Exception {
  ClassLoader classLoader = application.getClass().getClassLoader();
  URL resource = classLoader.getResource(jsonFilePath);
  File file = new File(resource.getPath());

  StringBuilder fileContents = new StringBuilder((int) file.length());
  Scanner scanner = new Scanner(file, "UTF-8");
  String lineSeparator = System.getProperty("line.separator");

  try {
    while (scanner.hasNextLine()) {
      fileContents.append(scanner.nextLine()).append(lineSeparator);
    }
    return fileContents.toString();
  } finally {
    scanner.close();
  }
}
 
Example 3
Source File: Java Regex 2 - Duplicate Words.java    From HackerRank-Solutions with The Unlicense 6 votes vote down vote up
public static void main(String[] args) {

        String regex = "\\b(\\w+)(\\W+\\1\\b)+";
        Pattern p = Pattern.compile(regex,  Pattern.CASE_INSENSITIVE);

        Scanner in = new Scanner(System.in);
        int numSentences = Integer.parseInt(in.nextLine());

        while (numSentences-- > 0) {
            String input = in.nextLine();

            Matcher m = p.matcher(input);

            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(m.group(), m.group(1));
            }

            // Prints the modified sentence.
            System.out.println(input);
        }

        in.close();
    }
 
Example 4
Source File: FloydWarshall.java    From Java with MIT License 6 votes vote down vote up
public static void main(String... arg) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the number of vertices");
    int numberOfVertices = scan.nextInt();
    int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
    System.out.println("Enter the Weighted Matrix for the graph");
    for (int source = 1; source <= numberOfVertices; source++) {
        for (int destination = 1; destination <= numberOfVertices; destination++) {
            adjacencyMatrix[source][destination] = scan.nextInt();
            if (source == destination) {
                adjacencyMatrix[source][destination] = 0;
                continue;
            }
            if (adjacencyMatrix[source][destination] == 0) {
                adjacencyMatrix[source][destination] = INFINITY;
            }
        }
    }
    System.out.println("The Transitive Closure of the Graph");
    FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices);
    floydwarshall.floydwarshall(adjacencyMatrix);
    scan.close();
}
 
Example 5
Source File: QHEAP1.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int n = sc.nextInt();
	a = new int[10];
	for (int i = 0; i < n; i++) {
		int q = sc.nextInt();
		int y;
		switch (q) {
		case 1:
			y = sc.nextInt();
			insert(y);
			break;
		case 2:
			y = sc.nextInt();
			delete(y);
			break;
		case 3:
			printMin();
			break;

		}
	}
	sc.close();
}
 
Example 6
Source File: FindTheRunningMedian.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	PriorityQueue<Integer> highers = new PriorityQueue<Integer>();
	PriorityQueue<Integer> lowers = new PriorityQueue<Integer>(new Comparator<Integer>() {
		public int compare(Integer i1, Integer i2) {
			return i2.compareTo(i1);
		}
	});
	int N = sc.nextInt();
	double meadian = 0;
	for (int i = 1; i <= N; i++) {
		int number = sc.nextInt();
		addNumber(number, lowers, highers);
		rebalance(lowers, highers);
		meadian = getMedian(lowers, highers);
		System.out.println(meadian);
	}
	sc.close();
}
 
Example 7
Source File: HandshakeExample.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		setConfig();
		System.out.println("Testing Pyro handshake and custom annotations. Make sure the server from the pyro handshake example is running.");
		System.out.println("Pyrolite version: "+Config.PYROLITE_VERSION);
		System.out.println("serializer used: " + Config.SERIALIZER);

		Scanner scanner = new Scanner(System.in);
		System.out.println("\r\nEnter the server URI: ");
		String uri = scanner.next().trim();
		System.out.println("Enter the secret code as printed by the server: ");
		String secret = scanner.next().trim();
		scanner.close();
		
		PyroProxy p = new CustomAnnotationsProxy(new PyroURI(uri));
		p.pyroHandshake = secret;
		p.correlation_id = UUID.randomUUID();
		System.out.println("Correlation id set to: "+p.correlation_id);
		p.call("ping");
		System.out.println("Connection Ok!");
		
		// tidy up:
		p.close();
	}
 
Example 8
Source File: DataParserDWI.java    From Beats with 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 9
Source File: PrimeSpiral1.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param args
 * the param args are not used
 */
public static void main(final String[] args) {
	
	Scanner sc = new Scanner(System.in);
	int n;
	double diagonal = 0, prim = 0;
	System.out.println("Enter the side length: ");
	n = sc.nextInt();
	int x = n * n;
	int substracter = n - 1;

	while (x >= 1 && substracter >= 0) {
		if (substracter == 0) {
			diagonal++;
			if (isPrime(x) == 1) {
				prim++;
			}
		} else {
			for (int i = 1; i <= 4; i++) {
				diagonal++;
				if (isPrime(x) == 1) {
					prim++;
				}
				x = x - substracter;	
			}	
		}
		substracter = substracter - 2;
	}
	
System.out.println("Prime numbers : " + prim);
System.out.println("Diagonal numbers : " + diagonal);
System.out.println("The ratio is: " + prim / diagonal * 100 + " %");
sc.close();
}
 
Example 10
Source File: soln.java    From HackerRank-solutions with MIT License 5 votes vote down vote up
public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
    System.out.println("================================");
    for (int i = 0; i < 3; i++) {
        String s1 = scan.next();
        int x = scan.nextInt();
        System.out.format("%-15s%03d%n", s1, x);
    }
    scan.close();
    System.out.println("================================");

}
 
Example 11
Source File: Client.java    From java-chat with MIT License 5 votes vote down vote up
public void run() throws UnknownHostException, IOException {
  // connect client to server
  Socket client = new Socket(host, port);
  System.out.println("Client successfully connected to server!");

  // Get Socket output stream (where the client send her mesg)
  PrintStream output = new PrintStream(client.getOutputStream());

  // ask for a nickname
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter a nickname: ");
  String nickname = sc.nextLine();

  // send nickname to server
  output.println(nickname);

  // create a new thread for server messages handling
  new Thread(new ReceivedMessagesHandler(client.getInputStream())).start();

  // read messages from keyboard and send to server
  System.out.println("Messages: \n");

  // while new messages
  while (sc.hasNextLine()) {
    output.println(sc.nextLine());
  }

  // end ctrl D
  output.close();
  sc.close();
  client.close();
}
 
Example 12
Source File: JavaScannerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenFindPatternUsingScanner_thenFound() throws IOException {
    final String expectedValue = "world";
    final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
    final Scanner scanner = new Scanner(inputStream);

    final String result = scanner.findInLine("wo..d");
    assertEquals(expectedValue, result);

    scanner.close();
}
 
Example 13
Source File: CreateClustersSample.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
private String readFile(String path) throws FileNotFoundException {
  Scanner scanner = new Scanner(new File(path), "UTF-8");
  try {
    return scanner.useDelimiter("\\Z").next();

  } finally {
    scanner.close();
  }
}
 
Example 14
Source File: OneGTableProducer.java    From snowflake-kafka-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final Enums.TestCases testCase)
{
  System.out.println("loading table: " + testCase.getTableName() +
    " in format: " + testCase.getFormatName() + " to Kafka");

  try
  {
    Scanner scanner = getFileScanner(testCase);
    while (scanner.hasNextLine())
    {
      JsonNode data = Utils.MAPPER.readTree(scanner.nextLine());
      send(Utils.TEST_TOPIC,
        OneGTable
          .newBuilder()
          .setCCUSTKEY(data.get("C_CUSTKEY").asLong())
          .setCNAME(data.get("C_NAME").asText())
          .setCADDRESS(data.get("C_ADDRESS").asText())
          .setCPHONE(data.get("C_PHONE").asText())
          .setCACCTBAL(data.get("C_ACCTBAL").asDouble())
          .setCMKTSEGMENT(data.get("C_MKTSEGMENT").asText())
          .setCCOMMENT(data.get("C_COMMENT").asText())
          .setCNATIONKEY(data.get("C_NATIONKEY").asLong())
          .build()
      );
    }
    scanner.close();
    close();
  }
  catch (Exception e)
  {
    e.printStackTrace();
    System.exit(1);
  }
  System.out.println("finished loading");
}
 
Example 15
Source File: Logger.java    From Everest with Apache License 2.0 5 votes vote down vote up
private String readFile(InputStream stream) {
    StringBuilder builder = new StringBuilder();
    Scanner scanner = new Scanner(stream);

    while (scanner.hasNext()) {
        builder.append(scanner.nextLine());
        builder.append("\n");
    }
    scanner.close();

    return builder.toString();
}
 
Example 16
Source File: FileUtil.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * Scan the /proc/mounts file and look for lines like this: /dev/block/vold/179:1 /mnt/sdcard
 * vfat
 * rw,dirsync,nosuid,nodev,noexec ,relatime,uid=1000,gid=1015,fmask=0602,dmask=0602,allow_utime=0020,
 * codepage=cp437,iocharset= iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0 When one is
 * found, split it into its
 * elements and then pull out the path to the that mount point and add it to the arraylist
 */
private static List<String> readMountsFile() {
  // some mount files don't list the default
  // path first, so we add it here to
  // ensure that it is first in our list
  List<String> mounts = new ArrayList<>();
  mounts.add(EXTERNAL_STORAGE_PATH);
  try {
    Scanner scanner = new Scanner(new File("/proc/mounts"));
    while (scanner.hasNext()) {
      String line = scanner.nextLine();
      if (line.startsWith("/dev/block/vold/") || line.startsWith("/dev/block//vold/")) {//
        String[] lineElements = line.split(" ");
        // String partition = lineElements[0];
        String element = lineElements[1];
        // don't add the default mount path
        // it's already in the list.
        if (!element.equals(EXTERNAL_STORAGE_PATH)) {
          mounts.add(element);
        }
      }
    }
    scanner.close();
  } catch (Exception e) {
    // e.printStackTrace();
  }
  return mounts;
}
 
Example 17
Source File: Day1DataTypes.java    From Hackerrank-Solutions with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	int i = 4;
	double d = 4.0;
	String s = "HackerRank ";

	Scanner scan = new Scanner(System.in);

	/* Declare second integer, double, and String variables. */
	int ii = scan.nextInt();
	scan.nextLine();
	double dd = scan.nextDouble();
	scan.nextLine();
	String ss = scan.nextLine();

	System.out.println(i + ii);
	System.out.println(d + dd);
	System.out.println(s + ss);

	/* Read and save an integer, double, and String to your variables. */
	// Note: If you have trouble reading the entire String, please go back and
	// review the Tutorial closely.

	/* Print the sum of both integer variables on a new line. */

	/* Print the sum of the double variables on a new line. */

	/*
	 * Concatenate and print the String variables on a new line; the 's' variable
	 * above should be printed first.
	 */

	scan.close();
}
 
Example 18
Source File: ReadInputFromKeyboard.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void read_input_from_keyboard() {
	
	// Variables to hold the month, day, and year
	int month;
	int day;
	int year;

	// Create a Scanner object for keyboard input.
	Scanner keyboard = new Scanner(System.in);

	// Get a month.
	System.out.print("Enter the number for a month: ");
	month = keyboard.nextInt();

	// Get a day.
	System.out.print("Enter the number for a day: ");
	day = keyboard.nextInt();

	// Get a two-digit year.
	System.out.print("Enter a two-digit year: ");
	year = keyboard.nextInt();
	
	System.out.println(month + "/" + day + "/" + year);
	
	keyboard.close();
}
 
Example 19
Source File: Test.java    From util4j with Apache License 2.0 4 votes vote down vote up
/**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
  	Test t=new Test();
  	Scanner sc=new Scanner(System.in);
  	System.out.print("请输入数据集数量:");
  	int dataNum=Integer.valueOf(sc.nextLine());
  	t.init(dataNum);
  	boolean exit=false;
  	for(;;)
  	{
  		if(exit) {
  			break;
  		}
  		System.out.print("S训练,T测试,E退出:");
  		String s=sc.nextLine();
      	switch (s) {
	case "S":{
		//挂起训练
		AtomicBoolean stop=new AtomicBoolean(false);
       	DecimalFormat fmt=new DecimalFormat("0.00000000");
       	CompletableFuture.runAsync(()->{
       		for(;;)
           	{
           		 long time=System.currentTimeMillis();
           		 t.train(1);
           		 time=System.currentTimeMillis()-time;
           		 System.out.println("(M菜单)训练耗时"+time+",平均误差:"+fmt.format(t.getAvgError()));
           		 if(stop.get())
           		 {
           			 break;
           		 }
           	}
       	});
       	//监听控制台输入
       	for(;;)
       	{
       		String m=sc.nextLine();
       		if("M".equals(m))
       		{
       			stop.set(true);break;
       		}
       	}
	}
		break;
	case "T":{
		for(;;)
       	{
       		System.out.print("请输入测试数值(-1退出):");
       		int testValue=-1;
       		try {
       			testValue=Integer.valueOf(sc.nextLine());
   			} catch (Exception e) {
   				continue;
   			}
       		if(testValue==-1)
       		{
       			break;
       		}
       		Type tp=t.test(testValue);
       		if(tp==null)
       		{
       			System.out.println("输入数值"+testValue+"类型未知");
       			continue;
       		}
       		System.out.println("输入数值"+testValue+"是:"+tp.desc);
       	}
	}
		break;
	case "E":
		exit=true;
		break;
	default:
		break;
	}
  	}
sc.close();
  }
 
Example 20
Source File: MassAndWeight.java    From levelup-java-exercises with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	
	// Create a Scanner object for keyboard input.
	Scanner keyboard = new Scanner(System.in);

	// Describe to the user what the program will do.
	System.out.println("Enter the object's mass:");

	double mass = keyboard.nextDouble();

	//close scanner
	keyboard.close();
	
	// pass mass to calculate weight
	double weight = calculateWeightInNewtons(mass);
	
	System.out.println("The object's weight is: " + weight);

	// get message per requirement
	String message = validWeight(weight);
	
	if (message.length() > 0) {
		System.out.println(message);
	}
	
}