当前位置: 首页>>代码示例>>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;未经允许,请勿转载。