扫描仪无法读取整个句子 - 扫描仪类的 next() 和 nextLine() 之间的区别

发布于 2024-09-30 13:40:09 字数 789 浏览 2 评论 0原文

我正在编写一个程序,允许用户输入数据然后输出它。它的 3/4 正确,但当它到达输出地址时,它只打印一个单词,让我们只说“Archbishop Street”的“Archbishop”。我该如何解决这个问题?

import java.util.*;

class MyStudentDetails{
    public static void main (String args[]){
        Scanner s = new Scanner(System.in);
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();

        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
}

I'm writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say only 'Archbishop' from 'Archbishop Street'. How do I fix this?

import java.util.*;

class MyStudentDetails{
    public static void main (String args[]){
        Scanner s = new Scanner(System.in);
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();

        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

揽月 2024-10-07 13:40:09

这种方法应该有效:

String s = sc.next();
s += sc.nextLine();

This approach should work:

String s = sc.next();
s += sc.nextLine();
浊酒尽余欢 2024-10-07 13:40:09

以这种方式初始化扫描仪,以便它使用换行符分隔输入。

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

有关更多详细信息,请参阅 JavaDoc

。 next() 获取字符串中的整行

Initialize the Scanner this way so that it delimits input using a new line character.

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

Refer the JavaDoc for more details

Use sc.next() to get the whole line in a String

未蓝澄海的烟 2024-10-07 13:40:09

我会使用 Scanner#nextLineaddress 属性的 next 相反。

此方法返回当前行的其余部分,不包括末尾的任何行分隔符。

由于这会返回整行,并由行分隔符分隔,因此用户可以不受任何限制地输入任何地址。

I would use Scanner#nextLine opposed to next for your address attribute.

This method returns the rest of the current line, excluding any line separator at the end.

Since this returns the entire line, delimited by a line separator, it will allow the user to enter any address without any constraint.

孤独岁月 2024-10-07 13:40:09
String s="Hi";
String s1="";

//For Reading Line by hasNext() of scanner 
 while(scan.hasNext()){
  s1 = scan.nextLine();
 }
System.out.println(s+s1);

/*This Worked Fine for me for reading Entire Line using Scanner*/
String s="Hi";
String s1="";

//For Reading Line by hasNext() of scanner 
 while(scan.hasNext()){
  s1 = scan.nextLine();
 }
System.out.println(s+s1);

/*This Worked Fine for me for reading Entire Line using Scanner*/
怀里藏娇 2024-10-07 13:40:09

Scanner 的默认分隔符是空格。检查 javadoc 了解如何更改此设置。

Default delimiter of Scanner is whitespace. Check javadoc for how to change this.

青衫儰鉨ミ守葔 2024-10-07 13:40:09
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        s += scan.nextLine();
        System.out.println("String: " + s);

    }
}
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        s += scan.nextLine();
        System.out.println("String: " + s);

    }
}
泪是无色的血 2024-10-07 13:40:09

不要直接使用 System.in 和 System.out,而是使用 Console 类 - 它允许您显示提示并读取整行输入(从而解决您的问题)一通电话:

String address = System.console().readLine("Enter your Address: ");

Instead of using System.in and System.out directly, use the Console class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:

String address = System.console().readLine("Enter your Address: ");
不再见 2024-10-07 13:40:09

我们可以使用 scan.nextLine 轻松完成。它将读取输入的其余部分直到最后。然后将其分配给您的变量。整个句子可以轻松打印
。这是为了您更好地理解的示例。

    String s = "HackerRank ";

    Scanner scan = new Scanner(System.in);


    String s2;



    scan.nextLine(); // read the rest of the line of input (newline character after the double token).
    s2 = scan.nextLine();



    /* Concatenate and print the String variables on a new line integer variables on a new line; 

    System.out.println(s + s2);

    scan.close();

}
}

We can easily done using scan.nextLine .It will read the rest of the input till the end. Then assign it to your variable. Entire sentence can be printed easily
. Here is the example for your better understanding.

    String s = "HackerRank ";

    Scanner scan = new Scanner(System.in);


    String s2;



    scan.nextLine(); // read the rest of the line of input (newline character after the double token).
    s2 = scan.nextLine();



    /* Concatenate and print the String variables on a new line integer variables on a new line; 

    System.out.println(s + s2);

    scan.close();

}
}

心头的小情儿 2024-10-07 13:40:09

我尝试了以下代码,但这并没有停止,因为没有中断条件,因此它总是等待输入,也许您可​​以添加中断条件

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s="";
        while(scan.hasNext())
        {
            s=scan.nextLine();
        }

        System.out.println("String: " +s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

I tried following code but this is not stopping as there is no break condition so it always waiting for input , may be you could add a condition for break

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s="";
        while(scan.hasNext())
        {
            s=scan.nextLine();
        }

        System.out.println("String: " +s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
街角卖回忆 2024-10-07 13:40:09

next() 只会存储第一个标记之前的输入。如果有两个单词“Hi There”,则表示有两个由空格(分隔符)分隔的标记。每次调用 next() 方法时,它只会读取一个标记。

如果输入是“你好!”

Scanner scan = new Scanner(System.in);
String str = scan.next()
System.out.println(str);

输出

,所以,如果您需要再次调用 next() 来获取下一个标记,这对于较长的字符串输入来说是低效的,

nextLine() 会抓取用户输入的整行,即使有空格

Scanner scan = new Scanner(System.in);
String str = scan.nextLine()
System.out.println(str);

输出

你好!

next() will only store the input up to the first token. if there are two words "Hi there" it means there are two tokens separated by space (delimiter). Every time you call the next() method it reads only one token.

if input is "Hi there !"

Scanner scan = new Scanner(System.in);
String str = scan.next()
System.out.println(str);

Output

Hi

So if you both the words you need to call next() again to get the next token which is inefficient for longer string input

nextLine() on the other hand grabs the entire line that the user enters even with spaces

Scanner scan = new Scanner(System.in);
String str = scan.nextLine()
System.out.println(str);

Output

Hi there !

残龙傲雪 2024-10-07 13:40:09
import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s="";
        while(scan.hasNext())
        {
            s=scan.nextLine();
        }

        System.out.println("String: " +s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s="";
        while(scan.hasNext())
        {
            s=scan.nextLine();
        }

        System.out.println("String: " +s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}
流心雨 2024-10-07 13:40:09

next() 只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next() 在读取输入后将光标置于同一行。

nextLine() 读取输入,包括单词之间的空格(即,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位在下一行。

要读取整行,您可以使用 nextLine()

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

for reading the entire line you can use nextLine()

乱了心跳 2024-10-07 13:40:09

java.util.Scanner; util - 包,扫描仪 - 类

  1. next() 读取空格之前的字符串。它在获得第一个空格后无法读取任何内容。
  2. nextLine() 读取整行。阅读直到行尾或“/n”。
    注意:不是下一行

(示例)

我的人生使命不仅仅是生存,而是蓬勃发展;

并且带着一些热情、一些同情心和一些幽默来做到这一点。

(输出)

  1. 我的

  2. 不仅仅是生存,而是蓬勃发展;

技巧:

如果您想阅读下一行,请检查 Java has 方法。

while (scanner.hasNext()) {
    scan.next();
}

while (scanner.hasNext()) {
    scan.nextLine();
}

java.util.Scanner; util - package, Scanner - Class

  1. next() reads the string before the space. it cannot read anything after it gets the first space.
  2. nextLine() reads the whole line. Read until the end of the line or "/n".
    Note: Not The Next line

(Example)

My mission in life is not merely to survive, but to thrive;

and to do so with some passion, some compassion, some humor.

(Output)

  1. My

  2. My mission in life is not merely to survive, but to thrive;

Tricks:

If you want to read the next line Check Java has method.

while (scanner.hasNext()) {
    scan.next();
}

while (scanner.hasNext()) {
    scan.nextLine();
}
海未深 2024-10-07 13:40:09

next() 会读取到遇到的空格,nextLine() 会读取到行尾。
扫描仪扫描 = new Scanner(System.in);
字符串地址 = scan.next();
s += scan.nextLine();

next() is read until the space of the encounter, and the nextLine() is read to the end of the line.
Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();

坦然微笑 2024-10-07 13:40:09

试试这个!

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        s = scan.nextLine();
        scan.close();
        System.out.println("String: " + s);
      
    }

Try this !!!

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        s = scan.nextLine();
        scan.close();
        System.out.println("String: " + s);
      
    }
澉约 2024-10-07 13:40:09

要获取完整地址,请

s.nextLine();//read the rest of the line as input

在之前添加

System.out.println("Enter Your Address: ");
String address = s.next();

To get the whole adress add

s.nextLine();//read the rest of the line as input

before

System.out.println("Enter Your Address: ");
String address = s.next();
烟─花易冷 2024-10-07 13:40:09

我将标记分隔符设置为换行模式,读取下一个标记,然后将分隔符放回原来的位置。

public static String readLine(Scanner scanner) {
        Pattern oldDelimiter = scanner.delimiter();
        scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
        String r = scanner.next();
        scanner.useDelimiter(oldDelimiter);
        return r;
}

I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.

public static String readLine(Scanner scanner) {
        Pattern oldDelimiter = scanner.delimiter();
        scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
        String r = scanner.next();
        scanner.useDelimiter(oldDelimiter);
        return r;
}
情绪 2024-10-07 13:40:09

“它只打印一个单词,让我们只说‘Archbishop Street’中的‘Archbishop’”

它只打印这个单词,因为扫描仪函数(例如 next()、nextInt() 等)每次只读取一个令牌。因此,该函数读取并返回下一个标记。

For example if you have: x y z
 s.next() will return x
 s.nextLine() y z

如果您想阅读整行“Archbishop Street”,请返回代码

String address = s.next(); // s = "Archbishop"
Then address += s.nextLine(); // s = s + " Street"

"it only prints a word lets say only 'Archbishop' from 'Archbishop Street"

It is only printing the word because Scanner functions such as next(), nextInt(), etc. read only a token at time. Thus this function reads and returns the next token.

For example if you have: x y z
 s.next() will return x
 s.nextLine() y z

Going back to your code if you want to read the whole line "Archbishop Street"

String address = s.next(); // s = "Archbishop"
Then address += s.nextLine(); // s = s + " Street"
对你的占有欲 2024-10-07 13:40:09

下面是使用 Java Scanner 类读取标准输入中的一行的示例代码。

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        System.out.println(s);
        scan.close();
    }
}

输入:

世界你好

输出:

世界你好

Below is the sample code to read a line in Standard input using Java Scanner class.

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        System.out.println(s);
        scan.close();
    }
}

Input:

Hello World

Output:

Hello World

夜唯美灬不弃 2024-10-07 13:40:09

下面的代码应该可以满足 yoiu 的要求:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    System.out.println(s);
    scan.close();
}

the below piece of code should do what yoiu are looking for:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    System.out.println(s);
    scan.close();
}
宛菡 2024-10-07 13:40:09
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
str += scanner.readLine();

String str = Scanner.next(); ===>它获取该行的第一个单词(hello world!! =>“hello”)
str +=scanner.nextLine(); ===>此方法返回当前行的其余部分,不包括末尾的任何行分隔符。 (你好世界!!=>“世界!!”)

Scanner scanner = new Scanner(System.in);
String str = scanner.next();
str += scanner.readLine();

String str = scanner.next(); ===> it fetch the 1st word of the line (hello world!! => "hello")
str += scanner.nextLine(); ===> This method returns the rest of the current line, excluding any line separator at the end. (hello world!! => " world!!")

旧夏天 2024-10-07 13:40:09

我也有同样的问题。这应该适合你:

s.nextLine();

I had the same question. This should work for you:

s.nextLine();
三岁铭 2024-10-07 13:40:09

使用 nextLine() 而不是 next() 将句子作为字符串输入。

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();

Use nextLine() instead of next() for taking sentence as string input.

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
我不咬妳我踢妳 2024-10-07 13:40:09

你可以这样做:

class MyStudentDetails{
    public static void main (String args[]){
         Scanner s = new Scanner(System.in);
         System.out.println("Enter Your Name: ");
         String name = s.nextLine();
         System.out.println("Enter Your Age: ");
         String age = s.nextLine();
         System.out.println("Enter Your E-mail: ");
         String email = s.nextLine();
         System.out.println("Enter Your Address: ");
         String address = s.nextLine();


         System.out.println("Name: "+name);
         System.out.println("Age: "+age);
         System.out.println("E-mail: "+email);
         System.out.println("Address: "+address);

    }
}

You can do this:

class MyStudentDetails{
    public static void main (String args[]){
         Scanner s = new Scanner(System.in);
         System.out.println("Enter Your Name: ");
         String name = s.nextLine();
         System.out.println("Enter Your Age: ");
         String age = s.nextLine();
         System.out.println("Enter Your E-mail: ");
         String email = s.nextLine();
         System.out.println("Enter Your Address: ");
         String address = s.nextLine();


         System.out.println("Name: "+name);
         System.out.println("Age: "+age);
         System.out.println("E-mail: "+email);
         System.out.println("Address: "+address);

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文