Are there any errors or suggestions to improve this code : // import import java
ID: 3829457 • Letter: A
Question
Are there any errors or suggestions to improve this code :
// import
import java.util.Scanner;
import java.util.Arrays;
public class GenXandY {
// Define constant array size
static final int ARRAYSIZE = 100;
public static void main(String[] args){
int x = 0;
int[] intValues = new int[ARRAYSIZE];
int y = 0;
for (int i=0; i<intValues.length; i++) {
intValues[i] = (int) (Math.random() * 100);
}
if (args.length == 2) { // Command line input
x = Integer.parseInt(args[0]); // Stores numbers on command line x and y
y = Integer.parseInt(args[1]);
System.out.println("Search for x and y values: " + args[0] + ", " + args[1]);
}else { // Exit program with instructions
System.out.println("Enter 2 sets of double number, e.g., 30 50 ");
System.exit(0);
}
// Sort the int array value
Arrays.sort(intValues);
// Print the sorted array
for (int i=0; i<intValues.length; i++) {
System.out.println("index is " + i + "," + "value is " + intValues[i]) ;
}
System.out.println("*****************************");
// Now we can search
// when using a binary search approach
// Remember we must sort before we can search
int lookFor = x;
int arrIndex = Arrays.binarySearch(intValues,lookFor);
System.out.println("The index with value " + x + " is : " + arrIndex);
System.out.println("The index with value " + y + " is : " + arrIndex);
}
}
Explanation / Answer
//Made a couple changes. No errors.
//GenXandY.java
// import
import java.util.Scanner;
import java.util.Arrays;
public class GenXandY {
// Define constant array size
static final int ARRAYSIZE = 100;
public static void main(String[] args){
int x = 0;
int[] intValues = new int[ARRAYSIZE];
int y = 0;
for (int i=0; i<intValues.length; i++) {
intValues[i] = (int) (Math.random() * 100);
}
if (args.length != 2) { // Command line input
System.out.println("Enter 2 sets of double number, e.g., 30 50 ");
System.exit(0);
}
x = Integer.parseInt(args[0]); // Stores numbers on command line x and y
y = Integer.parseInt(args[1]);
System.out.println("Search for x and y values: " + args[0] + ", " + args[1]);
// Sort the int array value
Arrays.sort(intValues);
// Print the sorted array
for (int i=0; i<intValues.length; i++) {
System.out.println("index is " + i + "," + "value is " + intValues[i]) ;
}
System.out.println("*****************************");
// Now we can search
// when using a binary search approach
// Remember we must sort before we can search
System.out.println("The index with value " + x + " is : " + Arrays.binarySearch(intValues,x));
System.out.println("The index with value " + y + " is : " + Arrays.binarySearch(intValues,y));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.