(程序分析题)阅读以下程序,分析输出结果: public class Test { public static void main(String args[]){ int score = 80; int x = -100; String type = score < 60 ? "不及格" : "及格"; int flag = x > 0 ? 1 : (x == 0 ? 0 : -1); "type= " + type); "flag= "+ flag); } }
时间: 2023-12-14 13:38:56 浏览: 38
此程序存在语法错误,应该在两个输出语句前加上 System.out.println() 。同时,程序的最后一行缺少一个左括号。
修改后的程序如下:
```
public class Test {
public static void main(String args[]) {
int score = 80;
int x = -100;
String type = score < 60 ? "不及格" : "及格";
int flag = x > 0 ? 1 : (x == 0 ? 0 : -1);
System.out.println("type= " + type);
System.out.println("flag= " + flag);
}
}
```
程序输出结果为:
```
type= 及格
flag= -1
```
解释如下:
- 变量 type 的值是根据 score 变量是否小于 60 决定的,因为 score 的值是 80,所以 type 的值为 "及格"。
- 变量 flag 的值是根据 x 变量是否大于 0 决定的,因为 x 的值是 -100,所以 x 不大于 0,接着判断 x 是否等于 0,由于 x 不等于 0,所以 flag 的值为 -1。
相关问题
public class test1 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); System.out.print("请输入学生的人数:"); int num=scan.nextInt(); int score[]=new int[num]; System.out.print("请输入"+num+"个学生的成绩:"); for (int i = 0; i < num.length; i++) { score[i]=scan.nextInt(); } } }错在哪里了
在这段代码中,`num`是一个`int`类型的变量,不是一个数组,所以不能使用`num.length`的方式获取其长度。应该改为使用`score.length`获取数组的长度。
正确的代码应该是这样的:
```java
public class test1 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.print("请输入学生的人数:");
int num=scan.nextInt();
int score[]=new int[num];
System.out.print("请输入"+num+"个学生的成绩:");
for (int i = 0; i < score.length; i++) {
score[i]=scan.nextInt();
}
}
}
```
这样就能正确编译和运行了。
package test01; public class Question1_3 { // 定义静态方法 gradeType,参数是整数成绩 // 返回值是成绩的类型:>= 90 返回优秀,>= 80 返回良好,>= 60 返回及格,< 60 返回不及格 // 不要修改下面代码,使程序输出:优秀 良好 及格 不及格 public static void main(String[] args) { System.out.println(gradeType(95)); System.out.println(gradeType(85)); System.out.println(gradeType(75)); System.out.println(gradeType(55)); } }
这段代码需要补充完整方法 `gradeType` 的实现,根据参数的成绩不同返回不同的字符串类型。可以使用如下代码:
```
package test01;
public class Question1_3 {
// 定义静态方法 gradeType,参数是整数成绩
// 返回值是成绩的类型:>= 90 返回优秀,>= 80 返回良好,>= 60 返回及格,< 60 返回不及格
public static String gradeType(int score) {
if (score >= 90) {
return "优秀";
} else if (score >= 80) {
return "良好";
} else if (score >= 60) {
return "及格";
} else {
return "不及格";
}
}
// 不要修改下面代码,使程序输出:优秀 良好 及格 不及格
public static void main(String[] args) {
System.out.println(gradeType(95));
System.out.println(gradeType(85));
System.out.println(gradeType(75));
System.out.println(gradeType(55));
}
}
```
这样就可以正确地输出不同分数对应的成绩类型了。