当前位置: 代码迷 >> java >> Java询问具有多个单词的String输入
  详细解决方案

Java询问具有多个单词的String输入

热度:104   发布时间:2023-07-31 13:47:04.0

我在使用Java询问Direct Whole名称时遇到问题。

System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.next();
System.out.println("Enter Name");
name = scan.next();
System.out.println("Enter Field of Specialization:");
field = scan.next();

System.out.println("ID               " + idnumber);
System.out.println("Name             " + name);
System.out.println("Specializtion    " + field );

当我在下面输入以下信息时:

ID = 100姓名= Brandon Sullano

它给了我这个结果

ID               100    
Name             Brandon    
Specializtion    Sullano

我希望Name是动态的,所以我甚至可以输入两个单词怎么做?
提前致谢..

采用:

name = scan.nextLine();

此外,如果ID号是一个整数,使用nextInt() (确保也将idnumber声明为int而不是string

固定代码:

System.out.println("DOCTOR");
System.out.println("Enter ID Number:");
idnumber = scan.nextInt();
scan.nextLine();

System.out.println("Enter Name");
name = scan.nextLine();
System.out.println("Enter Field of Specialization:");
field = scan.nextLine();

System.out.println("ID               " + idnumber);
System.out.println("Name             " + name);
System.out.println("Specializtion    " + field );

使用next()将在空格之前获取所有输入。 nextLine()将在按下return之前获取所有输入。

更多关于Scanner

专业提示:在大多数情况下,您将使用scan.nextLine()而不是scan.next()因此您可能希望养成使用它的习惯。

试试这段代码:

import java.util.Scanner;

public class DoctorDoctor {

    public static void main (String [] args) {

        int idnumber;
        String name, field;

        Scanner sc = new Scanner(System.in);

        System.out.println("DOCTOR");

        /** Assuming ID number is an integer value */
        System.out.print("Enter ID Number: ");
        idnumber = sc.nextInt();
        sc.nextLine(); // This is important, for clearing the new line character

        System.out.print("Enter Name: ");
        name = sc.nextLine();

        System.out.print("Enter Field of Specialization: ");
        field = sc.nextLine();

        System.out.println();
        System.out.printf("%-15s: %d%n", "ID Number", idnumber);
        System.out.printf("%-15s: %s%n", "Name", name);
        System.out.printf("%-15s: %s%n", "Specialization", field);

        sc.close();
    }
}

输入/输出示例:

DOCTOR
Enter ID Number: 100
Enter Name: Brandon
Enter Field of Specialization: Heart Surgeon

ID Number      : 100
Name           : Brandon
Specialization : Heart Surgeon

既然你说scan.nextLine() “不起作用”,我建议使用BufferedReader

BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
//in your code:
int idnumber = Integer.parseInt(br.readLine());
String name = br.readLine();
String field = br.readLine(); 

您必须导入java.io.BufferedReaderjava.io.InputStreamReader

  相关解决方案