当前位置: 动力学知识库 > 问答 > 编程问答 >

Unable to break out of For Loop in Java

问题描述:

I am a beginner and was making a small program to practice what i have learnt.

I was writing code to check the grade of a student.

This is the 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 the roll number of the student: ");

rollNo = inputter.nextInt();

System.out.println("Thank you. Now, please enter the student's name: " );

studentName = inputter.next();

for(int i=0; ; i++){

System.out.println("Please enter a valid examination type, i.e FA or SA: ");

String examType = inputter.next();

examType = examType.toUpperCase();

if(examType == "FA" || examType == "SA"){

break;

}

}

}

}

The problem I am facing is that even though I enter a valid examType, the For loop doesn't break.

网友答案:

You need to use String.equals().

Scanner.next() returns a String. Using == on a string doesn't give any errors but will test reference equality instead of value equality. It won't return true even if the strings are equal in value.

Correct code:

if(examType.equals("FA") || examType.equals("SA")){
    break;
}

EDIT
OP mentioned in a comment that the loop is to run without ending until hitting break. You can create an infinite loop in either of these two ways:

for(;;){
    //runs infinitely
}

OR

while(true){
    //runs infinitely
}

Both of these infinite loops are broken with break. Also, you use less memory (albeit a small and almost insignificant difference) because you don't have a counter variable. In the next-to-impossible case that the user enters invalid input so many times that the integer overflows, not having a variable eliminates this risk. You also save processor time because there isn't an instruction to allocate memory or add one to the number.

网友答案:
public static void main(String args[]) {
  String studentName;
  int rollNo = 0;
  Scanner inputter = new Scanner(System.in);

  System.out.println("Please enter the roll number of the student: ");
  rollNo = inputter.nextInt();

  System.out.println("Thank you. Now, please enter the student's name: " );
  studentName = inputter.next();

  for(int i=0; ; i++){
    System.out.println("Please enter a valid examination type, i.e FA or SA: ");
    String examType = inputter.next();
    examType = examType.toUpperCase();
    if(examType.equals("FA") || examType.equals("SA")){
        break;
    }
  }
}

This is working fine.

网友答案:

You haven't set a limit, for example

for(int i = 0; i < somevalue; i++)

otherwise a while loop might be a better choice like:

while(examType.equals("FA") || examType.equals("SA")
网友答案:

For best coding practice the usage of equals operation for Strings like below code snippet as per Sonar compliance standard.

("SA".equals (examType))

分享给朋友:
您可能感兴趣的文章:
随机阅读: