如何解决如何在if循环中要求输入特定条件
在check_mark()方法中,如果我为PHYSICS放置了错误的标记(位于第二个位置a [1]),即mark> 100,则进入if循环,它必须要求输入相同的PHYSICS标记,但是,再次从a [0]开始,即MATHS ...与英语相同,再次从MATHS开始。
请帮助我解决这个问题,它必须要求输入错误输入的特定标记...。
故障代码:
import java.util.Scanner;
class averageMark
{
static int no_of_students=2;
static int a[]=new int[3];
static int no_of_subjects=a.length;
static String b[]=new String[]{"MATHS","PHYSICS","ENGLISH"};
static int avg;
static int total_marks=0;
static Scanner sc=new Scanner(system.in);
void check_mark()
{
for (int j = 0; j < 3; j++)
{
System.out.print("Enter "+b[j]+" mark: ");
a[j]=sc.nextInt();
if(a[j]>100)
{
System.out.println("Please provide correct mark which is equal to or below 100");
check_mark();
}
}
}
public static void main( String[] args )
{
for (int i = 0; i < no_of_students; i++)
{
averageMark check=new averageMark();
check.check_mark();
for (int k = 0; k < no_of_subjects; k++)
{
total_marks+=a[k];
}
avg=total_marks/no_of_subjects;
System.out.println();
System.out.println("The average is: "+avg);
if(avg>=70)
{
System.out.println();
System.out.println("!!!Qualified!!!");
}
else
{
System.out.println();
System.out.println("!!!Not qualified!!!");
}
System.out.println();
}
sc.close();
}
}
解决方法
如果标记不正确,则不应调用check_mark方法。您应该减少索引
void check_mark() {
for (int j = 0; j < 3; j++) {
System.out.print("Enter "+b[j]+" mark: ");
a[j]=sc.nextInt();
if(a[j]>100) {
System.out.println("Please provide correct mark which is equal to or below 100");
j--;
}
}
}
,
您还可以使用while()循环来实现它;
void check_mark()
{
for (int j = 0; j < 3; j++)
{
System.out.print("Enter "+b[j]+" mark: ");
a[j]=sc.nextInt();
while(a[j]>100){
System.out.println("Please provide correct mark which is equal to or below 100");
a[j] = sc.nextInt();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。