scanner.next and nextLine

一般用掃瞄器物件(Scanner)時,若依下法,
在讀數字後,再讀文字,會有讀不到文字情況,


  Scanner sc = new Scanner(System.in);
  int i = sc.nextInt(); // 讀數字,換行字元未讀走
  String s = sc.nextLine(); // 讀換行前字串,會收到空字串


這時,建議改用如下寫法,


  Scanner sc = new Scanner(System.in);
  int i = sc.nextInt(); // 讀數字,換行字元未讀走
  String s = sc.nextLine(); // 故意用nextLine讀走下一換行前字串及換行字元
  String s = sc.nextLine(); // 再用nextLine重新讀下一換行前字串及換行字元

  Scanner sc = new Scanner(System.in);
  int i = sc.nextInt(); // 讀數字,換行字元未讀走
  String s = sc.next(); // 讀下一個空格隔開前文字,這樣非空格文字仍可讀到


如下測試範例 Test2.java 可自行試看看.

---- Test2.java -----------


/*
  Test2.java

  >javac Test2.java

  >java Test2
  input i=123
  input s=
  input s2=456
  i=123, s=, s2=456, end

*/
import java.util.*;

public class Test2
{
  public static void main(String[] arg)
  {
    Scanner sc = new Scanner(System.in);
    System.err.printf("input i=");
    int i = sc.nextInt();

    System.err.printf("input s=");
    String s = sc.nextLine();
    // 前面有讀數字,後面文字會讀不到,只收到空字串

    System.err.printf("\ninput s2=");
    String s2 = sc.nextLine();

    System.err.printf("i=%d, s=%s, s2=%s, end\n",i,s, s2);
  }
}

沒有留言:

how to deal with metric scale inconsistency in topn recommendation evaluation

🎯 推薦系統一般會回傳前 N 個排名的物品清單給用戶,稱為 Top‑N 推薦。 遇到推薦模型須要訓練及評估時,習慣先蒐集用戶與物品的互動資料,再將資料拆分成沒有重疊的訓練集及測試集。 模型在訓練時只看得到訓練集,評估時則拿測試集作為驗證的標準答案,以免作...

總網頁瀏覽量