个性化阅读
专注于IT技术分析

如何在Java中获取字符串输入

点击下载

本文概述

Java nextLine()方法

Scanner类的nextLine()方法用于从用户那里获取字符串。它在java.util.Scanner类中定义。 nextLine()方法读取文本, 直到行尾为止。读完该行后, 它将光标移至下一行。

该方法的签名是:

public String nextLine()

该方法返回被跳过的行。它不接受任何参数。当找不到任何行时, 则抛出NoSuchElementException。如果关闭扫描仪, 它还会引发IllegalStateException。

nextLine()方法的示例

import java.util.*;
class UserInputDemo1
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);	//System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();				//reads string 
System.out.print("You have entered: "+str);		      
}
}

输出:

如何在Java中获取字符串输入

Java next()方法

Java next()方法可以在找到空间ID之前读取输入。它无法读取由空格分隔的两个单词。读取输入后, 它将光标保留在同一行中。

该方法的签名是:

public String next()

该方法从此扫描器返回下一个完整令牌。它不接受任何参数。如果没有更多可用的令牌, 则抛出NoSuchElementException。如果关闭扫描仪, 它还会引发IllegalStateException。

next()方法的示例

import java.util.*;
class UserInputDemo2
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);  //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.next();   //reads string before the space
System.out.print("You have entered: "+str);		      
}
}

输出:

如何在Java中获取字符串输入

我们可以看到该方法将跳过Java之后编写的所有内容, 并且仅读取Java一词。


赞(0)
未经允许不得转载:srcmini » 如何在Java中获取字符串输入

评论 抢沙发

评论前必须登录!