Reputation: 21
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]);
}
}
}
Upvotes: 2
Views: 15257
Reputation: 11
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.
Upvotes: 1
Reputation: 178263
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.
Upvotes: 2
Reputation: 41281
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.
Upvotes: 1