Java 数组和方法的问题
如何让程序从输入文件中读取一组整数。目标是将它们存储在一个数组中,然后显示比输入值更大的值。另外,创建一个名为greater_than_n()的方法,该方法接受整数数组和整数n。此方法的目的是显示大于n的数字Java 数组和方法的问题,java,Java,如何让程序从输入文件中读取一组整数。目标是将它们存储在一个数组中,然后显示比输入值更大的值。另外,创建一个名为greater_than_n()的方法,该方法接受整数数组和整数n。此方法的目的是显示大于n的数字 import java.util.Scanner; import java.io.*; public class Lab5 // File Name{ public static void main(String[] args) throws IOException { Scann
import java.util.Scanner;
import java.io.*;
public class Lab5 // File Name{
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
File Integers = new File("Integers.txt");
Scanner inputReader = new Scanner(Integers);
String line = inputReader.nextLine();
System.out.print(line);
inputReader.close();
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < Integers.length; index++)
{
if(Integers[index] > userAction)
{
System.out.print(Integers + " ");
}
}
}
import java.util.Scanner;
导入java.io.*;
公共类Lab5//文件名{
公共静态void main(字符串[]args)引发IOException
{
扫描仪用户输入=新扫描仪(System.in);
File Integers=新文件(“Integers.txt”);
Scanner inputReader=新扫描仪(整数);
String line=inputReader.nextLine();
系统输出打印(行);
inputReader.close();
System.out.print(“输入整数:”);
int userAction=userInput.nextInt();
System.out.println(“输入文件中大于“+userAction+”的数字为:”;
for(int index=0;indexuserAction)
{
系统输出打印(整数+“”);
}
}
}
}打印Arrayobject时,您需要打印数组的索引,这可以通过使用:
System.out.print(numbers[index]).
你查错了。循环应该迭代到数组的长度。然后,如果要打印数组中较大的数字,请检查每个元素是否大于输入数字。如果是,请在索引中打印数字
Scanner userInput = new Scanner(System.in);
int[] numbers = {2, -4, 6, 8, 19};
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < numbers.length; index++) {
if(numbers[index] > userAction)
System.out.print(numbers[index] + " ");
}
Scanner userInput=新扫描仪(System.in);
int[]数={2,-4,6,8,19};
System.out.print(“输入整数:”);
int userAction=userInput.nextInt();
System.out.println(“输入文件中大于“+userAction+”的数字为:”;
for(int index=0;index用户操作)
系统输出打印(数字[索引]+“”);
}
您在循环的每一步都打印出数组,要打印出一个数字,您应该更改System.out.print(数字)代码>用于系统输出打印(数字[索引])代码>
如果您只想打印大于输入的数字(userAction=3
,例如,输出应该是6、8、19
),则您的算法中存在错误。您的算法只需打印出数组userAction
时间。要修复此问题,可以使用以下代码段:
for (int index = 0; index < numbers.length; index++)
{
if (numbers[index] > userAction) {
System.out.print(numbers[index]);
}
}
for(int index=0;index用户操作){
系统输出打印(编号[索引]);
}
}
请学习循环和数组。。。第一个错误-循环的限制(索引
,而应该是索引
)。第二个错误-循环正文并从数组输出数据(System.out.print(数字);
,而应该是System.out.print(数字[index]);
)如何让程序从输入文件中读取一组整数。目标是将它们存储在一个数组中,然后显示比输入值更大的值。另外,创建一个名为greater_than_n()的方法,该方法接受整数数组和整数n。此方法的目的是显示大于n的数字