简体   繁体   中英

Type mismatch: cannot convert from String to int

I'm trying to write a Java code for my java class, and I'm getting the following error message when I run the code:

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

Here is the assignment:

"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."

This is what I have so far:

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]);
         }

     }
}

The next method returns a String and it can't be automatically converted to an int . Call nextInt instead.

integer = inputStream.nextInt();

You may also want to call hasNextInt() to determine if what's next on the Scanner is actually an integer.

You need to parse the integer first use Scanner#nextInt() :

integer = inputStream.nextInt();

That will then read a series of characters from the input, and convert them to an integer. If the input is invalid (not an integer, or too large), an exception will be thrown and your program will terminate.

My Dear friend you have used scanner to get the input as an integer but you have used inputstream.next();

but as your input is a integer you have to use inputstream.nextInt(); because next() is used to get a string and nextInt() to get a Integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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