【问题标题】:How to overcome \n(Enter) using charAt() and br.skip()?如何使用 charAt() 和 br.skip() 克服 \n(Enter)?
【发布时间】:2016-02-15 18:45:47
【问题描述】:

在这个给定的程序中,名称显示为空白。原因是我们使用了read()readLine() 方法。

//Employee details

import java.io.*;

public class Empdata {
    public static void main(String[] args) throws IOException {

        // create BufferedReader object to accept data from keyboard
        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));

        // accept employee details
        System.out.print("Enter id:");
        int id = Integer.parseInt(br.readLine());

        System.out.print("Enter sex(M/F):");
        char sex = (char) br.read();

        System.out.print("Enter name:");
        String name = br.readLine();

        // display the employee details
        System.out.println("Id:" + id);
        System.out.println("Sex:" + sex);
        System.out.println("Name:" + name);
    }
}

输出:

输入 id:10
输入性别(M/F):M
输入姓名:id:10
性别:M
名称:

【问题讨论】:

  • 不要使用<br> 分隔行。如果您想发布代码,请使用代码示例选项(编辑器菜单中的{} 图标)。
  • 它对我来说无法正常工作,为什么不能编辑并显示给我,以便下次编辑对我有很大帮助。
  • 如果您想获得与<br/> 相同的效果并且您不在代码示例中,也可以使用两个空格然后使用enter 按钮创建换行符。
  • 没问题。随意编辑您的答案(代码应为code blocks,而不是粗体)。

标签: java string bufferedreader


【解决方案1】:

有两种方法可以解决这个问题:

  1. br.readLine().charAt(0)
  2. br.skip(2)
public class Empdata {
    public static void main(String[] args) throws IOException {

        // create BufferedReader object to accept data from keyboard
        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));

        // accept employee details
        System.out.print("Enter id:");
        int id = Integer.parseInt(br.readLine());

        System.out.print("Enter sex(M/F):");
        char sex = (char) br.read();
        //Solution #1 : char sex = br.readLine().charAt(0)

        //Solution #2 : skip 2 characters if using (char) br.read()
        br.skip(2)

        System.out.print("Enter name:");
        String name = br.readLine();

        // display the employee details
        System.out.println("Id:" + id);
        System.out.println("Sex:" + sex);
        System.out.println("Name:" + name);
    }
}

输出:

Enter id:10
Enter sex(M/F):M
Enter name:Vinay
id:10
sex: M
Name:Vinay

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多