import java.util.*;
public class test2
{
public static void main(String [] args)
{
int mark;
int sum = 0;
int student = 1;
for (student = 1; student <= 10; student++)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0)
{
sum = sum + mark;
}
else
{
student = 50;
}
}
System.out.println("sum is" + sum);
}
}
我想更改此代码以更好地适应目的并摆脱任何低效率我认为虽然循环比if else循环更好但我不知道如何解决这个问题。
答案 0 :(得分:1)
sc.nextLine()
)nextInt()
student = 50;
退出循环?这就是break
的用途。答案 1 :(得分:0)
您应该按如下方式更改方法:
public static void main(String[] args) {
int mark;
int sum = 0;
int student = 1;
Scanner sc = new Scanner(System.in);
while (student <= 10) {
System.out.println("Enter mark: ");
mark = sc.nextInt();
if (mark != 0) { // check if mark is not 0
sum = sum + mark; // increment the mark
} else {
break; // exit the loop
}
student++;
}
System.out.println("Sum is: " + sum);
}
然后,如果您输入标记0
,它将立即退出循环。
答案 2 :(得分:0)
import java.util.*;
public class test2
{
public static void main(String [] args)
{
int sum = 0;
Scanner sc = new Scanner(System.in); // Declare outside loop, you only need one instance
for (int student = 1; student <= 10; student++)
{
System.out.println("enter mark");
int mark = sc.nextInt();
if (mark <= 0) // If mark is negative
{
break; // Exit loop
}
sum += mark; // Increment sum by mark
}
System.out.println("sum is" + sum);
}
}
我认为0的标记应该是有效的输入,所以你可能想要使用`mark&lt; 0'而不是