繁体   English   中英

类型不匹配:无法从String转换为int

[英]Type mismatch: cannot convert from String to int

我正在尝试为我的java类编写Java代码,并且在运行代码时收到以下错误消息:

"Type mismatch: cannot convert from String to int;"

这是作业:

"Write a program that reads in a single digit number from the keyboard into an
integer variable. Your program will then print the number spelled out. If the user
types in a number that is more than one digit, your program must print an error
message. If the user types in a negative number, your program should print the word
"negative" before the digit spelled out."

这是我到目前为止的内容:

import java.util.Scanner;

public class ReadsNumber{

    public static void main(String[] args){

        String[] a = new String[10];

         a[0] = "Zero";
         a[1] = "One";
         a[2] = "Two";
         a[3] = "Three";
         a[4] = "Four";
         a[5] = "Five";
         a[6] = "Six";
         a[7] = "Seven";
         a[8] = "Eight";
         a[9] = "Nine";

         Scanner inputStream = new Scanner(System.in);  
         int integer;

         while(true){
             System.out.println("Input an integer: ");
             integer = inputStream.next();
             if (integer < 0)
                 System.out.println("negative");
             else if (integer > 9)
                 System.out.println("error");
             else 
                 System.out.println(a[integer]);
         }

     }
}

next方法返回String ,并且不能自动将其转换为int 而是调用nextInt

integer = inputStream.nextInt();

您可能还想调用hasNextInt()来确定Scanner上接下来的内容是否实际上是整数。

您需要 使用Scanner#nextInt() 解析整数

integer = inputStream.nextInt();

然后,它将从输入中读取一系列字符,并将其转换为整数。 如果输入无效(不是整数或太大),则将引发异常,并且程序将终止。

亲爱的朋友,您曾经使用扫描器将输入作为整数获取,但是您已经使用了inputstream.next();

但由于您的输入是整数,因此必须使用inputstream.nextInt(); 因为next()用于获取字符串,而nextInt()用于获取整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM