954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

ArrayOutofBounds

Im having arrayoutofbounds error on my code.

import java.io.*;
class s{
	public static void main(String args[]) throws IOException{
		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
		String[] a = {"X","C","O","M","P","U","T","E","R","S"};		
		System.out.println("Enter Price: ");
		String b = in.readLine();
		for(int i=0;i<b.length();i++){
			System.out.print(a[b.charAt(i)]);
		}
	}
}


what am i doing wrong here? The output should be if i input 35, should be MU.

pickachu
Newbie Poster
9 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

and why should that be so? charAt gives the character value at the index indicated.
'3' does not yield 3 though.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

In other words, read the API docs for Integer and its parse methods, and see if there is something there that can help you.

And find out what the difference between a char and an int is, as you can use a char as an int (as you've done here), but its value won't be what you seem to be expecting (find an ASCII character code table).

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

Thank, I needed to convert it into integer. Anyway, I encountered a new problem, How do I get the value of a special character like a PERIOD?

pickachu
Newbie Poster
9 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

You just cast it. In Java a char is actually just like an int, it only depends on how you use it.

// Declaration of char c, initialized with the character 'a'.
char c = 'a'; 
// For int value of the character, cast to int: (int).   
int i = (int) c;
// Do some work.
i++;
// Get the character back from the int by casting to char: (char).
c = (char) i;
// Now you see why 'b' comes after 'a' in the ascii table.
System.out.println(c);


Black Box

Black Box
Junior Poster in Training
62 posts since Nov 2007
Reputation Points: 60
Solved Threads: 7
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You