當前位置: 首頁>>代碼示例>>Java>>正文


Java Scanner.hasNext方法代碼示例

本文整理匯總了Java中java.util.Scanner.hasNext方法的典型用法代碼示例。如果您正苦於以下問題:Java Scanner.hasNext方法的具體用法?Java Scanner.hasNext怎麽用?Java Scanner.hasNext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.Scanner的用法示例。


在下文中一共展示了Scanner.hasNext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getResponseFromHttpUrl

import java.util.Scanner; //導入方法依賴的package包/類
/**
 * 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.
 * @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();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}
 
開發者ID:fjoglar,項目名稱:android-dev-challenge,代碼行數:26,代碼來源:NetworkUtils.java

示例2: load

import java.util.Scanner; //導入方法依賴的package包/類
private static void load(Field[] f, Scanner sc) throws InvalidFormatException, IllegalAccessException, TypeNotImplementedException{
    for(Field ff : f){
        if(sc.hasNext() && ff.getName().equals(sc.next())){
            if(ff.getType().equals(int.class)){
                ff.setInt(null,sc.nextInt());
            }
            else if (ff.getType().equals(boolean.class)){
                ff.setBoolean(null, sc.nextBoolean());
            }
            else{
                throw new TypeNotImplementedException();
            }
        }
        else{
            throw new InvalidFormatException();
        }         
    }
}
 
開發者ID:Famousjasper,項目名稱:Jollgren,代碼行數:19,代碼來源:Settings.java

示例3: getDisplayName

import java.util.Scanner; //導入方法依賴的package包/類
/**
 * Tries to fetch the current display name for the user
 *
 * @param id the id of the user to check
 * @return the current display name of that user
 * @throws IOException           if something goes wrong
 * @throws VoxelGameLibException if the user has no display name
 */
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
    URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
    System.out.println(url.toString());
    Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
    if (scanner.hasNext()) {
        String json = scanner.nextLine();
        try {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
            if (json.length() > 0) {
                return (String) ((JSONObject) jsonArray.get(0)).get("name");
            }
        } catch (ParseException ignore) {
        }
    }

    throw new VoxelGameLibException("User has no name! " + id);
}
 
開發者ID:VoxelGamesLib,項目名稱:VoxelGamesLibv2,代碼行數:27,代碼來源:MojangUtil.java

示例4: source

import java.util.Scanner; //導入方法依賴的package包/類
public void source(String contents) throws SQLException {
    Scanner s = new Scanner(contents);
    s.useDelimiter("(;(\r)?\n)|(--\n)");
    Connection connection = null;
    Statement statement = null;
    try {
        Class.forName(getDriverClass());
        connection = DriverManager.getConnection(url, this.user, password);
        statement = connection.createStatement();
        while (s.hasNext()) {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/")) {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0) {
                statement.execute(line);
            }
        }
    }
    catch (ClassNotFoundException ex) {
        throw new SQLException("Cannot locate JDBC driver class", ex);
    }

    finally {
        s.close();
        if (statement != null)
            statement.close();
        if (connection != null)
            connection.close();
    }
}
 
開發者ID:CenturyLinkCloud,項目名稱:mdw-demo,代碼行數:34,代碼來源:MariaDBEmbeddedDb.java

示例5: analyseText

import java.util.Scanner; //導入方法依賴的package包/類
static void analyseText(File fin, HashTable<Integer> counts) {
	try {
		Scanner scf = new Scanner(fin);
		scf.useDelimiter("[^\\p{IsAlphabetic}]+");
		// ^ Isto serve para especificar que o separador de "tokens" no scanner
		// será qualquer sequência de 1 ou mais carateres não alfabéticos.
		// Assim, cada token devolvido por scf.next() é uma palavra no sentido
		// mais convencional: uma sequência composta apenas de letras!

		String prevWord = null; // serve para guardar a palavra anterior

		while (scf.hasNext()) { // Processa cada palavra
			// palavra atual: é lida do scanner e normalizada:
			String currWord = scf.next().toLowerCase();

			// Completar...
			if (prevWord != null){
				// variavel com o bigrama
				String bigram = prevWord + " " + currWord;
				// quantas vezes apareceu o bigrama 
				int bigramCount = 0;
				// se já apareceu obtem a chave para de pois a incrementar
				if (counts.contains(bigram)) {
					bigramCount = counts.get(bigram);
				}
				counts.set(bigram, bigramCount+1);
			} 
			prevWord = currWord;
		}
		scf.close();
	}
	catch (IOException e) {
		err.printf("ERROR: %s\n", e.getMessage());
		exit(1);
	}
}
 
開發者ID:ZePaiva,項目名稱:Prog2,代碼行數:37,代碼來源:BigramCount.java

示例6: updateSchema

import java.util.Scanner; //導入方法依賴的package包/類
private void updateSchema(String tableName){
    String path = "data/myDB/"+tableName+"/schema.txt";
    File file = new File(path); //Se carga el esquema
    try {
        Scanner inputStream = new Scanner(file);
        while (inputStream.hasNext()) {
            this.dataSchema = getSchemaFromString(inputStream.nextLine(), path);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
 
開發者ID:andcastillo,項目名稱:fdp2017,代碼行數:14,代碼來源:Indexer.java

示例7: readMountsFile

import java.util.Scanner; //導入方法依賴的package包/類
/**
 * Read /proc/mounts. This is a set of hacks for versions below Kitkat.
 * @return list of mounts based on the mounts file.
 */
private static List<String> readMountsFile() {
  String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
  List<String> mounts = new ArrayList<>();
  mounts.add(sdcardPath);

  Timber.d("reading mounts file begin");
  try {
    File mountFile = new File("/proc/mounts");
    if (mountFile.exists()) {
      Timber.d("mounts file exists");
      Scanner scanner = new Scanner(mountFile);
      while (scanner.hasNext()) {
        String line = scanner.nextLine();
        Timber.d("line: %s", line);
        if (line.startsWith("/dev/block/vold/")) {
          String[] lineElements = line.split(" ");
          String element = lineElements[1];
          Timber.d("mount element is: %s", element);
          if (!sdcardPath.equals(element)) {
            mounts.add(element);
          }
        } else {
          Timber.d("skipping mount line: %s", line);
        }
      }
    } else {
      Timber.d("mounts file doesn't exist");
    }

    Timber.d("reading mounts file end.. list is: %s", mounts);
  } catch (Exception e) {
    Timber.e(e, "Error reading mounts file");
  }
  return mounts;
}
 
開發者ID:Elias33,項目名稱:Quran,代碼行數:40,代碼來源:StorageUtils.java

示例8: printData

import java.util.Scanner; //導入方法依賴的package包/類
static void printData(File file) throws FileNotFoundException {
	out = new Scanner(file);
	while (out.hasNext())
		System.out.println(out.nextLine());
}
 
開發者ID:nkg447,項目名稱:Alfred,代碼行數:6,代碼來源:Alfred.java

示例9: send

import java.util.Scanner; //導入方法依賴的package包/類
public void send() {
    if (loadConfig() != 0) {
        return;
    }

    producerProps.setProperty("bootstrap.servers", server);  //update
    producer = new KafkaProducer<>(producerProps);

    String key = msg.getType();
    String jsonMessage = msg.toJSONString();

    System.out.println("--------------------- preview your message -------------------------");
    System.out.printf("kafka topic:%s\n", topic);
    System.out.printf("message type:%s\n", type);
    System.out.println("message content:");
    System.out.println(JSON.toJSONString(msg, SerializerFeature.PrettyFormat));
    System.out.println("-------------------------------------------------------------------------");

    System.out.println("send this message(y/n)?");
    Scanner scanner = new Scanner(System.in);

    while (scanner.hasNext()) {
        String cmd = scanner.next().trim();
        if ("N".equalsIgnoreCase(cmd)) {
            System.out.println("give up to send message!");
            return;
        }
        if ("Y".equalsIgnoreCase(cmd)) {
            byte[] message = jsonMessage.getBytes();

            try {
                Future<RecordMetadata> result = producer.send(new ProducerRecord<>(topic, key, message), null);
                result.get();
                //logger.info(String.format("to_topic=%s, key=%s, value=%s", topic, key, jsonMessage));
                //System.out.println(jsonMessage);
                System.out.println("message send ok!");

            } catch (Exception err) {
                err.printStackTrace();
                System.out.println("message send fail!");
            } finally {
                producer.close();
            }
            return;
        }
    }
}
 
開發者ID:BriData,項目名稱:DBus,代碼行數:48,代碼來源:ControlMessageSender.java

示例10: testEncoding

import java.util.Scanner; //導入方法依賴的package包/類
public String testEncoding(String inputS) {
    char input[] = new char[unicode_max_length];
    int codept = 0;
    char uplus[] = new char[2];
    StringBuffer output;
    int c;

    /* Read the input code points: */

    input_length = 0;

    Scanner sc = new Scanner(inputS);

    while (sc.hasNext()) {  // need to stop at end of line
        try {
            String next = sc.next();
            uplus[0] = next.charAt(0);
            uplus[1] = next.charAt(1);
            codept = Integer.parseInt(next.substring(2), 16);
        } catch (Exception ex) {
            fail(invalid_input, inputS);
        }

        if (uplus[1] != '+' || codept > Integer.MAX_VALUE) {
            fail(invalid_input, inputS);
        }

        if (input_length == unicode_max_length) fail(too_big, inputS);

        if (uplus[0] == 'u') case_flags[input_length] = false;
        else if (uplus[0] == 'U') case_flags[input_length] = true;
        else fail(invalid_input, inputS);

        input[input_length++] = (char)codept;
    }

    /* Encode: */

    output_length[0] = ace_max_length;
    try {
        output = Punycode.encode((new StringBuffer()).append(input, 0, input_length), case_flags);
    } catch (Exception e) {
        fail(invalid_input, inputS);
        // never reach here, just to make compiler happy
        return null;
    }

    testCount++;
    return output.toString();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:51,代碼來源:PunycodeTest.java

示例11: readCategories

import java.util.Scanner; //導入方法依賴的package包/類
private static String readCategories() {
    ClassLoader classLoader = SearchCategoryParser.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream("categories.json");
    Scanner scanner = new Scanner(stream).useDelimiter("\\A");
    return scanner.hasNext() ? scanner.next() : "";
}
 
開發者ID:MontealegreLuis,項目名稱:yelpv3-java-client,代碼行數:7,代碼來源:SearchCategoryParser.java

示例12: convertStreamToString

import java.util.Scanner; //導入方法依賴的package包/類
/**
 * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
 */
@NonNull
static private String convertStreamToString(@NonNull InputStream is) {
    Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
 
開發者ID:SysdataSpA,項目名稱:SDHtmlTextView,代碼行數:9,代碼來源:HtmlTextView.java

示例13: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main( String[] args ) throws Exception {
	System.out.println( "開始生成License文件,當前支持以下模式:" );
	System.out.println( "0. 測試License文件,查看本地機器碼" );
	System.out.println( "1. 單機模式-僅驗證License文件的有效性" );
	System.out.println( "2. 時限模式-增加時限驗證" );
	System.out.println( "3. 聯網模式-需聯網驗證" );
	System.out.println( "請選擇對應的模式,回車確認:" );
	int mode = LicenseClient.MODE_SINGLE;
	@SuppressWarnings ( "resource" )
	Scanner sc = new Scanner( System.in );

	int step = 0;
	String s0 = "";
	String s1 = "";
	while ( sc.hasNext() ) {
		while ( step == 0 ) {
			int m = sc.nextInt();
			
			switch( m ){
			case 0:
				s_test();
				break;
			case 1:
				mode = LicenseClient.MODE_SINGLE;
				step = 1;
				break;
			case 2:
				mode = LicenseClient.MODE_INTIME;
				step = 1;
				break;
			case 3:
				mode = LicenseClient.MODE_ONLINE;
				step = 1;
				break;
			}

			if ( step == 0 ) {
				System.out.println( "模式選擇錯誤,請重新選擇:" );
			} else {
				System.out.println( "選擇模式為:" + m );
				System.out.println( "你可以輸入任意字符串作為自定義初始私鑰種子,長度為8~16:" );
			}
		}

		while ( step == 1 ) {
			if ( s0.equalsIgnoreCase( "" ) ) {
				s0 = sc.next();
				System.out.println( "請確認你使用的種子內容:" );
			}
			if ( s1.equalsIgnoreCase( "" ) ) {
				s1 = sc.next();
				if ( s0.equalsIgnoreCase( s1 ) ) {
					step = 2;
				} else {
					s0 = "";
					s1 = "";

					System.out.println( "內容不一致,請重新輸入:" );
				}
			}
		}
		
		if( step == 2 ) break;
	}

	String seed = s0;
	switch ( mode ) {
	case LicenseClient.MODE_SINGLE:
		s_generate_single( seed );
		break;
	}
}
 
開發者ID:aiyoyoyo,項目名稱:jeesupport,代碼行數:73,代碼來源:LicenseUtils.java

示例14: getFileDetails

import java.util.Scanner; //導入方法依賴的package包/類
public void getFileDetails() {

		InputStream is = getClass().getClassLoader()
				.getResourceAsStream("spring-annotationconfig.xml");

		Scanner sc1 = new Scanner(is);
		while (sc1.hasNext()) {

			System.out.println(sc1.nextLine());
		}

	}
 
開發者ID:Illusionist80,項目名稱:SpringTutorial,代碼行數:13,代碼來源:FileHelper2.java

示例15: showFileContent

import java.util.Scanner; //導入方法依賴的package包/類
public static void showFileContent(InputStream is) {

		Scanner sc1 = new Scanner(is);
		while (sc1.hasNext()) {

			System.out.println(sc1.nextLine());
		}

	}
 
開發者ID:Illusionist80,項目名稱:SpringTutorial,代碼行數:10,代碼來源:BasicSpringResourceSample.java


注:本文中的java.util.Scanner.hasNext方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。