有一个程序,用户将 10 个 int 值输入到数组中。最后,我需要提取不同的值并显示它们。添加了我的第二个 for 循环,它将确定该值是否不同(即,如果该数字出现多次,则仅显示一次)。
例如,假设我传入数字: 1, 2, 3, 2, 1, 6, 3, 4, 5, 2 不同的数组应该只包含数字 {1, 2, 3, 6, 4, 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: …Run Code Online (Sandbox Code Playgroud) 测试代码以查找数组中的min和max元素.我找到最大值的代码很好..但是我的min打印出"数组中的最小元素:0".我可能有一个小错误让我失去了大声笑.
public void deleteMin() {
// set value for comparision starting from the beginning of the array
int arrayMin = arr[0];
for (int j = 0; j < nElems; j++) {
if (arr[j] < arrayMin) {
arrayMin = arr[j];
}
// insert delete functionality
}
System.out.println("Minimum element in the array: " + arrayMin);
}
Run Code Online (Sandbox Code Playgroud) 编写一个程序,从文本文件中读取数字并测试它们以查看它们是否为素数.文本文件由以下数字组成:98,76,84,69,92,83,88,90,72,66.第一个数字,98不是素数,但第二个数字(76)应该作为Prime .我打印出来的结果显示所有数字都是Not Prime,这是不正确的.
import java.io.*;
import java.util.Scanner;
public class AssignFive_FileRead {
public static void main(String[] args) throws IOException {
int number;
int calc = 0;
int i = 2;
File myFile = new File("Numbers.txt");
Scanner inputFile = new Scanner(myFile);
// Check to see if file exists
if (!myFile.exists()) {
System.out.println("Error: file cannot be found");
System.exit(0);
} else {
System.out.println("File has been found, starting operation...");
}
// Reading numbers from text file
while (inputFile.hasNext()) {
number = inputFile.nextInt();
// Begin calculation …Run Code Online (Sandbox Code Playgroud)