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

时间:2014-05-27 23:34:39

标签: java

我正在尝试为我的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]);
         }

     }
}

3 个答案:

答案 0 :(得分:2)

next method returns a String,它无法自动转换为int。请改为呼叫nextInt

integer = inputStream.nextInt();

您可能还想致电hasNextInt()以确定Scanner上的下一个实际上是否为整数。

答案 1 :(得分:1)

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

integer = inputStream.nextInt();

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

答案 2 :(得分:1)

亲爱的朋友,您使用过扫描仪将输入作为整数获取,但您已使用$( document ).tooltip();

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