Home > Java > javaTutorial > body text

How to get input string using Scanner in Java?

王林
Release: 2023-04-24 09:28:06
forward
3207 people have browsed it

1.next method

If the entered valid characters are followed by a space, next() will use the space as the terminator. Therefore, if there are spaces in the middle of the input string, the complete string cannot be obtained using the next method.

import java.util.Scanner;
 
public class TestScanner1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if (scan.hasNext()) {
            // next方式接收字符串
            String str1 = scan.next();
            System.out.println("输入的数据为:" + str1);
        }
    }
}
Copy after login

You can see that the java string is not output.

2.nextLine method

nextLine() uses Enter as the terminator, that is to say, the nextLine() method returns the value before entering the Enter key. all characters.

import java.util.Scanner;
 
public class TestScanner2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            // 从键盘接收数据
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
    }
}
Copy after login

The above is the detailed content of How to get input string using Scanner in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template