Hey everyone,


I was doing an exercise from Java book and I didn't get how this code works.. I know how the switch statement works. However, I don't understand why they pass a number to the Random class and also to the .nextInt() method on rand. And also, I am not sure where the alphabets are coming from. I'm assuming that the variable c converts the letter a to an integral value and adds 26 to it?

Would anyone be happy to walk me through the code? This will be GREAT.

Thanks, folks.

Random rand = new Random(47);
	for(int i=0; i < 100; i++){
		int c = rand.nextInt(26) + 'a';
		println((char) c + ", " + c + ": ");
		switch(c){
			case 'a':
			case 'e':
			case 'i':
			case 'o':
			case 'u': 
				println("vowel \n");
				break;
			case 'y':
			case 'w': 
				println("Sometimes a vowel \n");
				break;
			default: println("consonant!");
		}
	}

have you checked the api?

'a' is a character, which has a numeric value as well, what is handled by the compiler.
so c will be the value found by rand.nextInt(26) + that numeric value. c is not converting anything, the compiler is doing that.

Yes. chars are numeric values that are interpreted as letters etc according to the Unicode system (same as ASCII for values <128). You can specify them either as a number or as a character in single quotes, or a mixture of the two.
It's a fact that the letters a-z occupy 26 consecutive values in that system, so you can safely say 'a' + 2 and Java will add 2 to the numeric value for 'a', and display the result as the corresponding character, which is 'c'.
If you add a random number between 0 and 25 to 'a' you will get a corresponding random char from 'a' to 'z'.
Now look up what nextInt(26) gives you.

Thanks guys for the explanation..

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.