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

Recommended Answers

All 4 Replies

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.

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.

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

How is random[] declared... String, int or what?

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.