Reputation: 73
I am attempting to write a program that outputs the name of a number when you input a number. It works fine for one digit numbers, but I've hit a roadblock. Whenever I input a number greater than 10, it gives me an ArrayOutOfBoundsException. I'm not quite sure why, for I haven't worked with arrays too long. I have only written code to output names for numbers upto 20 till now. Here is the code:
package numericname;
import java.util.Scanner;
public class NumericName {
static String[] Ones = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
static String[] Mids = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
System.out.println("Enter a number");
x = in.nextInt();
if(x/10 <= 1)
ones(x);
if(x/10 > 1 && x/10 < 2)
mids(x);
}
public static void ones(int x) {
System.out.println(Ones[x]);
}
public static void mids(int x) {
x -= 11
System.out.println(Mids[x]);
}
}
I added the x - 11 to make the number equal its name in the string array, but it still doesn't work. What am I doing wrong? Thanks!
Upvotes: 0
Views: 66
Reputation: 742
Two problems, both relating to you being a victim of Integer Division:
In Java, when you divide two integers, the result is the value of the equation with the decimal truncated. This means that the decimal part is 'cut-off'. For example: 11 / 10 = 1
, 19 / 10 = 1
, 9 / 10 = 0
Now for the problems:
To fix this:
Change it to if (x <= 10)
To fix this, change it to either:
if(x < 20)
if(x / 10 == 1)
Upvotes: 1
Reputation: 93
It's because, x/10
still gives you 1
. It's an integer division. You have to change it to floating point.
Just change x/10
and x/20
to x/10.0
and x/20.0
everywhere.
Or just cast x
to float
during division.
Example
if((float)x/10 <= 1)
ones(x);
if((float)x/10 > 1 && (float)x/10 < 2)
mids(x);
Upvotes: 0
Reputation: 1
The problem lies in the fact that the division you are attempting is integer division, and this will not work as you expect. Any number from 11 to 19 will yield x/10 as 1 and then the function
ones(x)
Will lead to an ArrayIndexOutOfBounds
Upvotes: 0
Reputation: 798
my suggested edit for the main() is as follows:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
System.out.println("Enter a number");
x = in.nextInt();
if(x <= 10) {
ones(x);
} else if(x < 20) {
mids(x);
}
}
Upvotes: 0
Reputation: 2922
I suppose there are two issues here :
Why are you trying to use multiple arrays, you can club the two. Secondly, why are using x/10, you can simply compare x<10 or x>10 && x<20.
Upvotes: 0
Reputation: 539
Your code is checking if (x/10 <= 1), so then the 10s will be true and drop into the ones code in this case. i.e. 11/10 == 1
Upvotes: 0