如何在JAVA中使用s.nextLine()进行字符串输入后打印第一个字符?
有人能建议我在这段代码中如何打印字符串的第一个字符吗如何在JAVA中使用s.nextLine()进行字符串输入后打印第一个字符?,java,Java,有人能建议我在这段代码中如何打印字符串的第一个字符吗 import java.util.*; class SortingMachine { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int N=sc.nextInt(); for(int i=1;i<=N;i++) {
import java.util.*;
class SortingMachine
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
for(int i=1;i<=N;i++)
{
String s;
s=sc.nextLine();
s=s.replaceAll("\\s","");
s=s.toLowerCase();
System.out.println(s.charAt(0));
}
}
}
使用sc.next代替sc.nextLine。
使用扫描仪后,请关闭扫描仪
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int i = 1; i <= N; i++) {
String s;
s = sc.next(); // -----------------------> change here!!!!
s = s.replaceAll("\\s", "");
s = s.toLowerCase();
System.out.println(s.charAt(0));
}
sc.close(); // close the Scanner!!!
}
我猜您得到的是StringOutOfBoundsException,因为sc.nextLine不会等待任何输入,它只会使扫描仪前进到当前行,并返回跳过的输入。问题是,没有更多的输入,所以它会得到一个空字符串。当您尝试打印空字符串中的第一个字符时,砰的一声
要修复此问题,扫描仪实际上需要等待用户输入内容。请参阅Jordi Castilla的答案。如果您需要整数
public class Tests {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String s = String.valueOf(N);
char[] arr = s.toCharArray();
System.out.print("First Characater: "+arr[0]);
sc.close(); // close the Scanner!!!
}
}
在这种情况下,你必须考虑两种边缘情况
1您期望的输入类型。如果是整数,则使用int N=sc.nextInt
2如果需要整数,则它必须小于整数最大值
但是如果使用字符串input=sc.nextLine;然后,您可以将任何类型的输入作为字符串。之后,您必须将其转换为所需的任何数据类型。并确保输入不是空字符串。看起来您的代码已经这样做了。此代码没有显示您希望它显示的功能是什么?在sc.nextInt…System.out.printlns.charAt0之后添加sc.nextLine;打印s的第一个字符是这句话的目的非常感谢你。之前我尝试使用sc.next,但没有关闭扫描仪。感谢您的澄清
public class Tests {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String s = String.valueOf(N);
char[] arr = s.toCharArray();
System.out.print("First Characater: "+arr[0]);
sc.close(); // close the Scanner!!!
}
}