• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Java: Best Way to read a file

经常在各种平台的online test里面不熟悉STDIN, STOUT,下面举个例子:

Input Format

There are three lines of input:

  1. The first line contains an integer.
  2. The second line contains a double.
  3. The third line contains a String.

Output Format

There are three lines of output:

1. String

2. Double

3. Int

Sample Input

42
3.1415
Welcome to HackerRank's Java tutorials!

Sample Output

String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42

Hi, I don't understand why we have to do a sc.nextLine(), then do it again sc.nextLine()...
Sometimes you have to clear the buffer to print the strings by command sc.nextLine();

Answer: After supplying data for int, we would hit the enter key. What nextInt() and nextDouble() does is it assigns integer to appropriate variable and keeps the
enter key unread in thekeyboard buffer. so when its time to supply String the nextLine() will read the enter key from the user thinking that the user has entered the enter key.
(that's we get empty output) . Unlike C, there is no fflush() to clean buffer, so we have to flush by not taking it in variable.


 1 import java.util.*;
 2 
 3 class Solution {
 4     
 5     public static void main(String[] args) {
 6         Scanner sc = new Scanner(System.in);
 7         int n = sc.nextInt();
 8         double x = sc.nextDouble();
 9         sc.nextLine();
10         String str = sc.nextLine();
11 
12 
13         System.out.println(str);
14         System.out.println(x);
15         System.out.println(n);
16     }
17 }

 

 

 

posted @ 2015-01-04 08:18  neverlandly  阅读(246)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3