java.util.Scanner#nextLine ( )源码实例Demo

下面列出了java.util.Scanner#nextLine ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Mathematics   文件: trig_calc.java
public static double tanh(){

        // Ask for user input
        System.out.print("Enter your number: ");

        // use scanner to read the console input
        Scanner scan = new Scanner(System.in);

        // Assign the user to String variable
        String input = scan.nextLine();

        // close the scanner object
        scan.close();

        // convert the string input to double
        double value = Double.parseDouble(input);
       
        // get the tanh of the angle
        double tanhValue = Math.tanh(value);
        System.out.println("tanh of " + input + " is " + tanhValue);
        return tanhValue;
    }
 
源代码2 项目: gocd   文件: OperatingSystem.java
private static String detectCompleteName() {
    String[] command = {"python", "-c", "import platform;print(platform.linux_distribution())"};
    try {
        Process process = Runtime.getRuntime().exec(command);
        Scanner scanner = new Scanner(process.getInputStream());
        String line = scanner.nextLine();
        OS_COMPLETE_NAME = cleanUpPythonOutput(line);
    } catch (Exception e) {
        try {
            OS_COMPLETE_NAME = readFromOsRelease();
        } catch (Exception ignored) {
            OS_COMPLETE_NAME = OS_FAMILY_NAME;
        }
    }
    return OS_COMPLETE_NAME;
}
 
源代码3 项目: openjdk-jdk8u   文件: SBCS.java
public static void genClass(String args[]) throws Exception {

        Scanner s = new Scanner(new File(args[0], args[2]));
        while (s.hasNextLine()) {
            String line = s.nextLine();
            if (line.startsWith("#") || line.length() == 0)
                continue;
            String[] fields = line.split("\\s+");
            if (fields.length < 5) {
                System.err.println("Misconfiged sbcs line <" + line + ">?");
                continue;
            }
            String clzName = fields[0];
            String csName  = fields[1];
            String hisName = fields[2];
            boolean isASCII = Boolean.valueOf(fields[3]);
            String pkgName  = fields[4];
            System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName);

            genClass0(args[0], args[1], "SingleByte-X.java.template",
                      clzName, csName, hisName, pkgName, isASCII);
        }
    }
 
源代码4 项目: netbeans   文件: AstPath.java
public AstPath(ASTNode root, int caretOffset, BaseDocument document) {
    try {
        // make sure offset is not higher than document length, see #138353
        int length = document.getLength();
        int offset = length == 0 ? 0 : caretOffset + 1;
        if (length > 0 && offset >= length) {
            offset = length - 1;
        }
        Scanner scanner = new Scanner(document.getText(0, offset));
        int line = 0;
        String lineText = "";
        while (scanner.hasNextLine()) {
            lineText = scanner.nextLine();
            line++;
        }
        int column = lineText.length();

        this.lineNumber = line;
        this.columnNumber = column;

        findPathTo(root, line, column);
    } catch (BadLocationException ble) {
        Exceptions.printStackTrace(ble);
    }
}
 
源代码5 项目: ForgeHax   文件: CsvFile.java
public void readFromFile() throws IOException {
  Scanner in = new Scanner(new BufferedReader(new FileReader(file)));
  try {
    in.useDelimiter(",");
    headerLine = in.nextLine(); // Skip header row
    while (in.hasNextLine()) {
      String srgName = in.next();
      String mcpName = in.next();
      String side = in.next();
      String comment = in.nextLine().substring(1);
      srgMemberName2CsvData.put(
          srgName, new CsvData(srgName, mcpName, Integer.valueOf(side), comment));
    }
  } finally {
    in.close();
  }
}
 
源代码6 项目: java-codes   文件: Client.java
public static void main(String[] args) {
    // use java 7 try-with-resource auto close resource.
    try (Socket client = new Socket(HOST, SERVER_PORT);
         DataInputStream in = new DataInputStream(client.getInputStream());
         DataOutputStream out = new DataOutputStream(client.getOutputStream())) {

        //创建系统输入扫描器,监听键盘输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please input word:");
        while (true){
            //获取键盘输入
            String word = scanner.nextLine();
            //发送给Server
            out.writeUTF(word);
            //接收Server 回应
            System.out.println(in.readUTF());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
/**
 * Read a file
 * @param filepath The file path to the file.
 * @return String the file contents
 */
public static String readFile(String filepath)
{
	String result ="";
	try {
	 Scanner sc = new Scanner(new File(filepath)); 
	    while (sc.hasNextLine()) 
	      result+="\r\n"+sc.nextLine();
	    sc.close();
	} catch (Exception e) {
		return "";
	}
	return result;
}
 
源代码8 项目: malmo   文件: SchemaHelper.java
static public boolean testSchemaVersionNumbers(String modVersion)
{
    // modVersion will be in three parts - eg 0.19.1
    // We only care about the major and minor release numbers.
    String[] parts = modVersion.split("\\.");
    if (parts.length != 3)
    {
        System.out.println("Malformed mod version number: " + modVersion + " - should be of form x.y.z. Has CMake been run?");
        return false;
    }
    String requiredVersion = parts[0] + "." + parts[1];
    System.out.println("Testing schemas against internal version number: " + requiredVersion);
    InputStream stream = MalmoMod.class.getClassLoader().getResourceAsStream("schemas.index");
    if (stream == null)
    {
        System.out.println("Cannot find index of schema files in resources - try rebuilding.");
        return false;   // Failed to find index in resources - check that gradle build has happened!
    }
    Scanner scanner = new Scanner(stream);
    while (scanner.hasNextLine())
    {
        String xsdFile = scanner.nextLine();
        String version = getVersionNumber(xsdFile);
        if (version == null || !version.equals(requiredVersion))
        {
            scanner.close();
            System.out.println("Version error: schema file " + xsdFile + " has the wrong version number - should be " + requiredVersion + ", actually " + version);
            return false;
        }
    }
    scanner.close();
    return true;
}
 
源代码9 项目: hottub   文件: DBCS.java
public static void genClass(String args[]) throws Exception {

        Scanner s = new Scanner(new File(args[0], args[2]));
        while (s.hasNextLine()) {
            String line = s.nextLine();
            if (line.startsWith("#") || line.length() == 0)
                continue;
            String[] fields = line.split("\\s+");
            if (fields.length < 10) {
                System.err.println("Misconfiged sbcs line <" + line + ">?");
                continue;
            }
            String clzName = fields[0];
            String csName  = fields[1];
            String hisName = ("null".equals(fields[2]))?null:fields[2];
            String type = fields[3].toUpperCase();
            if ("BASIC".equals(type))
                type = "";
            else
                type = "_" + type;
            String pkgName  = fields[4];
            boolean isASCII = Boolean.valueOf(fields[5]);
            int    b1Min = toInteger(fields[6]);
            int    b1Max = toInteger(fields[7]);
            int    b2Min    = toInteger(fields[8]);
            int    b2Max    = toInteger(fields[9]);
            System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName);
            genClass0(args[0], args[1], "DoubleByte-X.java.template",
                    clzName, csName, hisName, pkgName,
                    isASCII, type,
                    b1Min, b1Max, b2Min, b2Max);
        }
    }
 
源代码10 项目: chipster   文件: Client.java
private static void acceptInputFromUser(Session senderSession, MessageProducer sender) throws JMSException {
    System.out.println("Type a message. Type COMMIT to send to receiver, type ROLLBACK to cancel");
    Scanner inputReader = new Scanner(System.in);

    while (true) {
        String line = inputReader.nextLine();
        if (line == null) {
            System.out.println("Done!");
            break;
        } else if (line.length() > 0) {
            if (line.trim().equals("ROLLBACK")) {
                System.out.println("Rolling back...");
                senderSession.rollback();
                System.out.println("Messages have been rolledback");
            } else if (line.trim().equals("COMMIT")) {
                System.out.println("Committing... ");
                senderSession.commit();
                System.out.println("Messages should have been sent");
            } else {
                TextMessage message = senderSession.createTextMessage();
                message.setText(line);
                System.out.println("Batching up:'" + message.getText() + "'");
                sender.send(message);
            }
        }
    }
}
 
@Override
public void run() {
  Scanner scanner = new Scanner(System.in);


  while (true) {
    List<Double> values = new ArrayList<>();
    System.out.println("Introduce the new reference point(between commas):");
    String s = scanner.nextLine() ;
    Scanner sl= new Scanner(s);
    sl.useDelimiter(",");
    try {
      while (sl.hasNext()){
        values.add(Double.parseDouble(sl.next()));
      }
    }catch (Exception e){//any problem
      values.add(0.0);
      values.add(0.0);
    }
    String cad="[";
    int i=0;
    for (Double val:values) {
      cad+=val +" ";
    }
    cad+="]";
    System.out.println("REF POINT: " + cad) ;

    observable.setChanged();

    observable.notifyObservers(new ObservedValue<>(values));
  }
}
 
源代码12 项目: mzmine2   文件: AgilentCsvReadTask.java
/**
 * Reads meta information on the file. This must be called with the keys in order, as it does not
 * reset the scanner position after reading.
 * 
 * @param scanner The Scanner which is reading this AgilentCSV file.
 * @param key The key for the metadata to return the value of.
 */
private String getMetaData(Scanner scanner, String key) {
  String line = "";
  while (!line.trim().startsWith(key) && scanner.hasNextLine()) {
    line = scanner.nextLine();
    if (line.trim().startsWith(key))
      return line.split(",", 2)[1].trim();
  }
  return null;
}
 
源代码13 项目: HackerRank-solutions   文件: soln.java
public static void main(String[] args) {
    /* Read input */
    Scanner scan = new Scanner(System.in);
    int i    = scan.nextInt();
    double d = scan.nextDouble();
    scan.nextLine();              // gets rid of the pesky newline
    String s = scan.nextLine();
    scan.close();
    
    /* Print output */
    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}
 
源代码14 项目: sofa-tracer   文件: LogTest.java
@Test
public void testLogback() throws IOException {
    Logger logger = LoggerFactory.getLogger(LogTest.class);
    logger.info("ssss");
    logger.info("hello world");

    SofaTracerSpan span = (SofaTracerSpan) this.sofaTracer.buildSpan("testCloneInstance")
        .asChildOf(sofaTracerSpan).start();
    span.setParentSofaTracerSpan(sofaTracerSpan);
    SofaTraceContextHolder.getSofaTraceContext().push(span);

    logger.info("childinfo1");

    SofaTraceContextHolder.getSofaTraceContext().pop();

    span.close();

    SofaTraceContextHolder.getSofaTraceContext().pop();

    logger.info("return to parent span");

    sofaTracerSpan.close();

    sofaTracer.close();
    fos.flush();
    fos.close();
    Scanner scanner = new Scanner(new FileInputStream("output.log"));
    String line1 = scanner.nextLine();
    String line2 = scanner.nextLine();
    String line3 = scanner.nextLine();
    String line4 = scanner.nextLine();

    Assert.assertTrue(line1 != null);
    Assert.assertTrue(line1.contains("ssss"));
    Assert.assertTrue(line1.contains(sofaTracerSpan.getSofaTracerSpanContext().getTraceId()));
    Assert.assertTrue(line1.contains("lgm"));

    Assert.assertTrue(line2 != null);
    Assert.assertTrue(line2.contains("hello world"));
    Assert.assertTrue(line2.contains(sofaTracerSpan.getSofaTracerSpanContext().getTraceId()));
    Assert.assertTrue(line2.contains("lgm"));

    Assert.assertTrue(line3 != null);
    Assert.assertTrue(line3.contains("childinfo1"));
    Assert.assertTrue(line3.contains(span.getSofaTracerSpanContext().getTraceId()));
    Assert.assertTrue(line3.contains("lgm"));

    Assert.assertTrue(line4 != null);
    Assert.assertTrue(line4.contains("return to parent span"));
    Assert.assertTrue(line4.contains(sofaTracerSpan.getSofaTracerSpanContext().getTraceId()));
    Assert.assertTrue(line4.contains("lgm"));

}
 
源代码15 项目: android-uninstall-feedback   文件: FeedbackUtils.java
public static boolean cancel() {
    try {
        if (processId != 0) {
            android.os.Process.killProcess(processId);
        }
        //通过ps查找弹卸载反馈的进程
        String processName = context.getPackageName() + ":feedback";
        Process p = Runtime.getRuntime().exec("ps");
        p.waitFor();
        Scanner scanner = new Scanner(p.getInputStream());
        List<String> tags = new ArrayList<>();

        int pidRow = -1;
        while (scanner.hasNextLine()) {
            String scannerStr = scanner.nextLine();
            if (scannerStr.contains(processName) || scannerStr.toLowerCase().contains("pid")) {
                while (scannerStr.contains("  ")) {
                    scannerStr = scannerStr.replaceAll("  ", " ").trim();
                }
                String pidStr = null;
                int pid = -1;
                if (scannerStr.toLowerCase().contains("pid")) {
                    tags = Arrays.asList(scannerStr.toLowerCase().split(" "));
                    pidRow = tags.indexOf("pid");//pid所在的列号
                } else if (pidRow != -1){
                    pidStr = scannerStr.split(" ")[pidRow];
                    if (!TextUtils.isEmpty(pidStr)) {
                        pid = Integer.valueOf(pidStr);
                        android.os.Process.killProcess(pid);
                        Log.d("DaemonThread", scannerStr + "\npidRow:" + pidRow + ", kill pid:" + pid);
                    }
                }
            }
        }
        return true;
    } catch (Exception e) {
        Log.d("DaemonThread", "cancel Exception => " + e.getMessage());
        if (BuildConfig.DEBUG) {
            e.printStackTrace();
        }
    }
    return false;
}
 
/**
 * This method returns the parsed record string in the form of
 * a map of two strings, consisting of a iteration aware attribute
 * names and its values
 *

 * @param  rawResult the raw query results to be parsed
 * @param queryParser The parsing mechanism being used to parse the data into groups
 * @param queryRegex The regex to be used to split the query results into groups. The regex MUST implement at least on named capture group "KEY" to be used to populate the table rows
 * @param lookupKey The regular expression number or the column of a split to be used for matching
 * @return  Table with attribute names and values where each Table row uses the value of the KEY named capture group specified in @param queryRegex
 */
protected Table<String, String, String> parseBatchResponse(String rawResult, String queryParser, String queryRegex, int lookupKey, String schema) {
    // Note the hardcoded record0.
    //  Since iteration is done within the parser and Multimap is used, the record number here will always be 0.
    // Consequentially, 0 is hardcoded so that batched and non batched attributes follow the same naming
    // conventions
    final String recordPosition = ".record0";

    final Table<String, String, String> results = HashBasedTable.create();

    switch (queryParser) {
        case "Split":
            Scanner scanner = new Scanner(rawResult);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                // Time to Split the results...
                String[] splitResult = line.split(queryRegex);

                for (int r = 0; r < splitResult.length; r++) {
                    results.put(splitResult[ lookupKey - 1 ], "enrich." + schema + recordPosition + ".group" + String.valueOf(r), splitResult[r]);
                }
            }
            break;
        case "RegEx":
        // prepare the regex
        Pattern p;
        // Regex is multiline. Each line should include a KEY for lookup
        p = Pattern.compile(queryRegex, Pattern.MULTILINE);

        Matcher matcher = p.matcher(rawResult);
        while (matcher.find()) {
            try {
                // Note that RegEx matches capture group 0 is usually broad but starting with it anyway
                // for the sake of purity
                for (int r = 0; r <= matcher.groupCount(); r++) {
                    results.put(matcher.group(lookupKey), "enrich." + schema + recordPosition + ".group" + String.valueOf(r), matcher.group(r));
                }
            } catch (IndexOutOfBoundsException e) {
                getLogger().warn("Could not find capture group {} while processing result. You may want to review your " +
                        "Regular Expression to match against the content \"{}\"", new Object[]{lookupKey, rawResult});
            }
        }
        break;
    }

    return results;
}
 
源代码17 项目: util4j   文件: Test.java
/**
   * @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();
  }
 
源代码18 项目: tutorials   文件: ScannerNextLineUnitTest.java
@Test(expected = IllegalStateException.class)
public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() {
    Scanner scanner = new Scanner("");
    scanner.close();
    String result = scanner.nextLine();
}
 
源代码19 项目: selenium-jupiter   文件: SeleniumJupiter.java
private static void resolveLocal(String[] args) {
    String browser = args[0];
    String version = "";
    String deviceName = "";
    String versionMessage = "(latest)";
    if (args.length > 1) {
        version = args[1];
        versionMessage = version;
    }
    if (args.length > 2) {
        deviceName = join(" ", copyOfRange(args, 2, args.length));
    }

    log.info("Using Selenium-Jupiter to execute {} {} in Docker", browser,
            versionMessage);

    try {
        config.setVnc(true);
        config.setBrowserSessionTimeoutDuration("99h0m0s");

        BrowserInstance browserInstance = new BrowserInstance(config,
                annotationsReader,
                BrowserType.valueOf(browser.toUpperCase()), NONE, empty(),
                empty());
        DockerDriverHandler dockerDriverHandler = new DockerDriverHandler(
                config, browserInstance, version, preferences);

        WebDriver webdriver = dockerDriverHandler.resolve(browserInstance,
                version, deviceName, config.getDockerServerUrl(), true);

        getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                cleanContainers(dockerDriverHandler, webdriver);
            }
        });

        log.info("Press ENTER to exit");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        scanner.close();

        cleanContainers(dockerDriverHandler, webdriver);

    } catch (Exception e) {
        log.error("Exception trying to execute {} {} in Docker", browser,
                versionMessage, e);
    }
}
 
源代码20 项目: thunder   文件: MainNode.java
static List<String> showIntroductionAndGetNodeList (ServerObject server, DBHandler dbHandler) {
    System.out.println("Thunder.Wallet NodeKey");
    System.out.println("Your public key is:     " + server.pubKeyServer.getPublicKeyAsHex());
    System.out.println();
    System.out.println("Nodes currently online: ");

    for (PubkeyIPObject ipObject : dbHandler.getIPObjects()) {
        System.out.format("%10s %-50s %48s%n", "", ipObject.hostname + ":" + ipObject.port, Tools.bytesToHex(ipObject.pubkey));
    }
    System.out.println();
    System.out.println("Choose pubkeys of nodes to connect to (random for complete random, empty when done)");

    List<String> nodeList = new ArrayList<>();
    while (true) {
        System.out.print(">>>> ");
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();

        if (s.equals("0")) {
            return null;
        } else if (s.equals("")) {
            return nodeList;
        } else if (s.equals(server.pubKeyServer.getPublicKeyAsHex())) {
            System.out.println("You cannot connect to yourself..");
        } else if (nodeList.contains(s)) {
            System.out.println("Pubkey already added to the list..");
        } else {
            ECKey key;
            try {
                key = ECKey.fromPublicOnly(Tools.hexStringToByteArray(s));
            } catch (Exception e) {
                System.out.println("Invalid pubkey..");
                continue;
            }

            System.out.println(key.getPublicKeyAsHex() + " added to list..");
            nodeList.add(s);
        }

    }
}