Java-接受字符输入时出现意外中断

Java的新手,很难弄清为什么它不起作用,在获取用户输入的一半途中,它意外地停止了运行。我评论了它的坏处。错误消息:“线程“ main”中的异常java.util.InputMismatchException”


有人可以帮忙吗?


import java.util.Scanner;


public class BasicInput {

   public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in);


      //Initializations

      int userInt = 0;

      double userDouble = 0.0;

      String userString = "";

      char character = '?';


      //Take User Input

      System.out.println("Enter integer: ");

      userInt = scnr.nextInt();

      System.out.println("Enter double: ");

      userDouble = scnr.nextInt();


      /* ERROR OCCURS HERE */


      System.out.println("Enter character: ");

      character = scnr.next().charAt(0);

      System.out.println("Enter string: ");

      userString = scnr.next();


      //Print User Input


      System.out.println(userString);

      System.out.print(character);

      System.out.print(userDouble);

      System.out.print(userInt);


      //Cast double to an integer

      int userInt2 = 0;

      userInt2 = (int)userDouble;

      System.out.print(userInt2);


      return;

   }

}


浮云间
浏览 141回答 2
2回答

一只名叫tom的猫

读取int而不是double,如下所示将其更改为double   //Take User Input  System.out.println("Enter integer: ");  userInt = scnr.nextInt();  System.out.println("Enter double: ");  userDouble = scnr.nextDouble();

慕斯709654

当您将scnr.nextInt()的值分配给userDouble时,会发生错误。您应该使用scnr.nextDouble()。同样,当您键入两次时,请使用“,”作为分隔符,而不是“。”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java