为什么一个个输进去可以输出,一下子全部输进去就会报错?哪里的问题?怎么改?
import java.util.Scanner;
class Plant{
String plant;
String name;
int acot;
public Plant(String plant, String name, int acot) {
this.plant = plant;
this.name = name;
this.acot = acot;
out();
}
public void out() {
System.out.println(name+"用"+acot+"小时种"+plant+"。");
}
}
public class oj1516 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int n1=sc.nextInt();
Plant s[]=new Plant[n];
for(int i=0;inew Plant(sc.next(),sc.next(),sc.nextInt());
}
for(int j=0;j-1;j++){
for(int k=j;kif(s[j].acot>s[k].acot){
tem=s[j];
s[j]=s[k];
s[k]=tem;
}
}
}
int sum=0;
int t=0;
for(int x=0;xif(sum<=10){
t++;
}
}
System.out.println(n1+"小时至多可以种"+t+"种植物。");
sc.close();
}
}
该回答引用GPTᴼᴾᴱᴺᴬᴵ
这个问题可能是由于输入不完整导致的。在一次输入多个值时,如果有输入未完成就按下了回车键,可能会导致下一次输入时出现异常。你可以通过在每次输入之前使用sc.hasNext()方法来检查是否有下一个输入,如果有则进行下一次输入,否则跳过当前输入。
修改后的代码如下:
import java.util.Scanner;
class Plant {
String plant;
String name;
int acot;
public Plant(String plant, String name, int acot) {
this.plant = plant;
this.name = name;
this.acot = acot;
out();
}
public void out() {
System.out.println(name + "用" + acot + "小时种" + plant + "。");
}
}
public class oj1516 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int n1 = sc.nextInt();
Plant s[] = new Plant[n];
for (int i = 0; i < n; i++) {
while (!sc.hasNext()) { // 检查是否有下一个输入
Thread.yield(); // 让出CPU时间片
}
s[i] = new Plant(sc.next(), sc.next(), sc.nextInt());
}
for (int j = 0; j < n - 1; j++) {
for (int k = j; k < n; k++) {
Plant tem;
if (s[j].acot > s[k].acot) {
tem = s[j];
s[j] = s[k];
s[k] = tem;
}
}
}
int sum = 0;
int t = 0;
for (int x = 0; x < n; x++) {
sum += s[x].acot;
if (sum <= 10) {
t++;
}
}
System.out.println(n1 + "小时至多可以种" + t + "种植物。");
sc.close();
}
}
在这里,我使用了while (!sc.hasNext())循环来检查是否有下一个输入,如果没有则调用Thread.yield()方法让出CPU时间片,让输入有足够的时间完成。需要注意的是,在输入完成后应该调用Scanner.close()方法来关闭Scanner对象,释放资源。
s[i]=new Plant(sc.next(),sc.next(),sc.nextInt());
你要根据你的输入语句来输入