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.

Recommended Answers

All 4 Replies

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

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

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?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.