A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

import java.util.Scanner;
public class 链表 {
    public static void main(String[] args) {

Scanner input=new Scanner(System.in);
          int g = input.nextInt();
          switch(g){
          case 1:
                 System.out.print("请输入ID: ");
                 String str=input.nextLine();
                 System.out.print("请输入name: ");
                 String stw=input.nextLine();
                 System.out.print("请输入sex: ");
                 String stf=input.nextLine();
                 break;
           case 2:
                break;
}
}}
为什么不能正常的输入ID,解决方案是什么????求解

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

1 个回复

倒序浏览

查Api得到以下:
nextLine
public String nextLine()此扫描器执行当前行,并返回跳过的输入信息。 此方法返回当前行的其余部分,不包括结尾处的行分隔符。当前位置移至下一行的行首。
因为此方法会继续在输入信息中查找行分隔符,所以如果没有行分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。
返回:
跳过的行
nextInt() 接收一个整型字符,nextline()读入一行文本,会读入"\n"字符,但"\n"并不会成为返回的字符串值的一部分、

结合你这个代码就是String str=input.nextLine();是将str设置为空白字符,因为 int g = input.nextInt();  g只接收到了数字,没有接收到"\n",被str接受
结合不同的方法从键盘读取字符输入时,有时不得不包含一条额外的nextLine()调用,以去除行的结束符
  1. Scanner input=new Scanner(System.in);
  2.         int g = input.nextInt();
  3.         switch(g){
  4.         case 1:
  5.                   [color=Red] String s=input.nextLine();//接收"/n"[/color]
  6.                System.out.print("请输入ID: ");
  7.                String str=input.nextLine();
  8.                System.out.print("请输入name: ");
  9.                String stw=input.nextLine();
  10.                System.out.print("请输入sex: ");
  11.                String stf=input.nextLine();
  12.                break;
  13.          case 2:
  14.               break;
  15. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马