Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public class Coursecheck {
public static void main(String args[])
{
String co[]=new String[9];
String ser=" ";
int flag=0;
Scanner s=new Scanner(System.in);
System.out.println("enter sub");
for(int i=0;i<3;i++)
	co[i]=s.nextLine();
System.out.println("enter search");
ser=s.nextLine();
for(int j=0;j<3;j++) {
	if(ser==co[j])
	{
		
		flag=1;
		break;
	}
}
if(flag!=1)
	System.out.println("course is not present");
else
	System.out.println("course is present");
}
}


What I have tried:

for(int j=0;j<3;j++) {
	if(ser==co[j])
	{
		
		flag=1;
		break;
	}
}
if(flag!=1)
	System.out.println("course is not present");
else
	System.out.println("course is present");


Everytime it's printing "course is not available" however it's available.What's wrong in the logic?
Posted
Updated 2-Jul-19 10:37am

1 solution

complete guess:
Is it possible that the following line of code is never true?

Java
if(ser==co[j])


ah, yes it is possible. NOw that I look at it closer you are doing ser (string)
comparison but the comparison in that line actually compares the two objects (and they are never equal.
Then, since it is never true, the flag never gets set to 1.

You have to do string comparison differently in Java. Change line to:
Java
if(ser.equals(co[j]))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900