0

im stuck on a question from the book, java in 2 semesters chapter 7.

2a) write a program that asks the user to input a string, followed by a single character, and then tests whether the string starts with that character.

public class StringTest {

	public static void main(String[] args) {
		
		String s;
		char c;
		
		//input string
		System.out.println("please enter a string: ");
		s = EasyScanner.nextString();
		
		//input char 
		System.out.println("please enter a character: ");
		c = EasyScanner.nextChar();
		
		//compare string and char
		if(s.charAt(0) == c){  
			System.out.println("string starts with the character entered");
		}
		
		else{
			System.out.println("string does not start with character entered");
		}
	}
}

im using a class called EasyScanner which helps in not calling the Scanner. Ok i think this is right for part a but im stuck on part b.

b) make your program work so that the case of the character is irrelevant.

*need help on this part*

Thanks in advance :)

3
Contributors
4
Replies
16
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0
if(s.toLowerCase().charAt(0) == c){  
			System.out.println("string starts with the character entered");
		}
		else if(s.toUpperCase().charAt(0) == c){
			System.out.println("string starts with the character entered");
		}
		else{
			System.out.println("string does not start with character entered");
		}

ok i worked it out :)

if there are other solutions please do post, thanks.
0

Hi Mudzy, welcome to DaniWeb.
Your code looks OK.
You could combine both "if" tests into one with a logical OR ( || ), which is a bit shorter, but a bit less clear maybe.
You could use the Character class to convert c to upper case, then use just one comparison to compare it to s.toUpperCase().charAt(0), which would save you one "if" test, but add a couple of method calls, so it's not a lot better really.

0
for(int i=0;i<random.length();i++){
 if(random[i]=="A"){
label2.setText(random(i));
   }
   it gives an error in this line if(random[i]=="A")
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.