Unable to break out of For Loop in Java -


i beginner , making small program practice have learnt. writing code check grade of student.

this code :

import java.util.*;

public class grader {   public static void main(string[] args) {      string studentname;     int rollno = 0;     scanner inputter = new scanner(system.in);      system.out.println("please enter roll number of student: ");     rollno = inputter.nextint();      system.out.println("thank you. now, please enter student's name: " );     studentname = inputter.next();      for(int i=0; ; i++){         system.out.println("please enter valid examination type, i.e fa or sa: ");         string examtype = inputter.next();         examtype = examtype.touppercase();         if(examtype == "fa" || examtype == "sa"){             break;         }     }  } 

}

the problem facing though enter valid examtype, loop doesn't break.

you need use string.equals().

scanner.next() returns string. using == on string doesn't give errors test reference equality instead of value equality. won't return true if strings equal in value.

correct code:

if(examtype.equals("fa") || examtype.equals("sa")){     break; } 

edit
op mentioned in comment loop run without ending until hitting break. can create infinite loop in either of these 2 ways:

for(;;){     //runs infinitely } 

or

while(true){     //runs infinitely } 

both of these infinite loops broken break. also, use less memory (albeit small , insignificant difference) because don't have counter variable. in next-to-impossible case user enters invalid input many times integer overflows, not having variable eliminates risk. save processor time because there isn't instruction allocate memory or add 1 number.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -