链接:
原题出处
来源:牛客网
读入N名学生的成绩,将获得某一给定分数的学生人数输出。
输入描述:
测试输入包含若干测试用例,每个测试用例的格式为
第1行:N
第2行:N名学生的成绩,相邻两数字用一个空格间隔。
第3行:给定分数
当读到N=0时输入结束。其中N不超过1000,成绩分数为(包含)0到100之间的一个整数。
输出描述:
对每个测试用例,将获得给定分数的学生人数输出。
示例1
输入
3
80 60 90
60
2
85 66
0
5
60 75 90 55 75
75
0
输出
1
0
2
一开始,我写了一个封装类来封装信息,并将该类添加到集合中。这样才可以保证输出0结束后记住输入的所有数据。
在idea上复制输入示例代码测试,输出的数据与输出示例一样但是通不过测试,后来查了一下网络上的,他们是按一组一组数据处理的不是将所有数据输入后在统一处理,但是这样将输入示例在idea上测试与输出示例不符但又可以通过。百思不得其解,无情!
这里先附上可以通过的代码:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int N=in.nextInt();
if(N==0){
return;
}
in.nextLine(); //吃个空格,nextLine()和next()以及nextInt()一起用一定要格外注意空格回车
String scores = in.nextLine();
int score = in.nextInt();
String[] s=scores.split(" ");
for(String t:s){
int i = Integer.parseInt(t);
if(i==score){
count++;
}
}
System.out.println(count);
}
}
下面的是封装的:
import java.util.*;
public class Day16{
//方法
public static int fun(int N,String scores,int theScore){
int count = 0;
String[] s = scores.split(" ");
for(int i = 0;i<N;i++){
int score = Integer.parseInt(s[i]);
if(theScore==score){
count++;
}
}
return count;
}
public static class Test{
int N;
String scores;
int theScore;
int count=0;
public Test(int N,String scores,int theScore){
this.N=N;
this.scores = scores;
this.theScore = theScore;
}
public void setCount(int count){
this.count = count;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
List<Test> list = new ArrayList<Test>();
int N=in.nextInt();
in.nextLine(); //吃空格
while(N!=0){
String scores=in.nextLine();/*
System.out.println(scores);*/
int theScore = in.nextInt();
list.add(new Test(N,scores,theScore));
N = in.nextInt();
in.nextLine();
}
for(int i = 0;i < list.size();i++){
Test test = list.get(i);
int count = fun(test.N,test.scores,test.theScore);
test.setCount(count);
}
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i).count);
}
}
}
如有错误还望指出哈!