Home >Java >javaTutorial >How to get input string using Scanner in Java?

How to get input string using Scanner in Java?

王林
王林forward
2023-04-24 09:28:063241browse

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);
        }
    }
}

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);
        }
    }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete