0
package newproj;

import java.util.Scanner;

public class MyFirstClass 

{

    public static void main(String[] args) 
    {
        char a;
        int b;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter value b: ");
        b= sc.nextInt();
        System.out.print("Enter char: ");
        a = sc.nextLine().charAt(0);
        System.out.println("This is "+a);
    }

}

运行时控制台上反映的错误是线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:-1。

有人可以教我如何在扫描整数后扫描字符。在 C 编程中,有“fflush(stdin)”来帮助 scanf 功能。所以,我一直在想换行符被扫描了。

4

2 回答 2

1

更改您的代码如下

    char a;
    int b;
    Scanner sc = new Scanner(System.in);
    Scanner sc1 = new Scanner(System.in);
    System.out.print("Enter value b: ");
    b= sc.nextInt();
    System.out.print("Enter char: ");
    a = sc1.nextLine().charAt(0);
    System.out.println("This is "+a);
于 2013-09-06T09:48:11.490 回答
1

逐行读取输入并将第一行解析为int. 如果它包含无效字符,NumberFormatException则会抛出 a。

public static void main(String[] args) throws NumberFormatException
{
    char a;
    int b;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter value b: ");
    b = Integer.parseInt(sc.nextLine());
    System.out.println("Enter char: ");
    a = sc.nextLine().charAt(0);
    System.out.println("This is "+a);
}
于 2013-09-06T09:47:57.737 回答