java - Switch Statement Inside a method of another class -
public int alphcheck(char check){ switch(check){ case 'a': return 1; break; case 'b': return 2; break; case 'c': return 3; break; case 'd': return 4; break; case 'e': return 5; break; case 'f': return 6; break; case 'g': return 7; break; case 'h': return 8; break; case 'i': return 9; break; case 'j': return 10; break; case 'k': return 11; break; case 'l': return 12; break; case 'm': return 13; break; case 'n': return 14; break; case 'o': return 15; break; case 'p': return 16; break; case 'q': return 17; break; case 'r': return 18; break; case 's': return 19; break; case 't': return 20; break; case 'u': return 21; break; case 'v': return 22; break; case 'w': return 23; break; case 'x': return 24; break; case 'y': return 25; break; case 'z': return 26; break; } }
ps.this done in class want able use method in main class, input letter, , return number/index letter. kept getting: method must return result of type int.
very confused. please help. thx.
here's question consider: happens if inputted letter isn't 1 of cases described?
while you may know you're feeding in letters, compiler doesn't know that, , because can't figure out return if 1 of cases defined isn't hit, emits error result. you'll need put in default
case, compiler knows method guaranteed return something:
switch(check) { case 'a': ... default: // return or maybe print/throw error }
a better solution may use fact chars
numbers in different form. example, 'a'
equivalent integer 97
(check out table here table of characters , ascii numerical equivalents). can math trick equivalent results:
public int alphcheck(char check) { return check - 'a' + 1; }
Comments
Post a Comment