In: Computer Science
Download the AllEqual.java file, and open it in jGrasp (or a text editor of your choice). This program takes a number of command line arguments, converts them to integers, and then determines if they all have the same value. An example run of the program is below, using the command-line arguments 1 2 3:
Are equal: false
A further example is shown below, with the command-line arguments 2 2:
Are equal: true
In the event that the program is given no arguments or only one argument, it should consider all the elements equal to each other.
public class AllEqual { // You must define the allEqual method, which will return // true if either: // 1.) The given array contains fewer than two elements, or... // 2.) All elements of the array are equal to each other. // As a hint, you only need to compare the first element // to all subsequent elements for this check. // // TODO - define your code below this comment // // DO NOT MODIFY parseStrings! public static int[] parseStrings(String[] strings) { int[] retval = new int[strings.length]; for (int x = 0; x < strings.length; x++) { retval[x] = Integer.parseInt(strings[x]); } return retval; } // DO NOT MODIFY main! public static void main(String[] args) { int[] argsAsInts = parseStrings(args); boolean areEqual = allEqual(argsAsInts); System.out.println("Are equal: " + areEqual); } }
The completed code is given below:
(*Note: Please up-vote. If any doubt, please let me know in the comments)
Full completed code:
public class AllEqual {
// You must define the allEqual method, which will return
// true if either:
// 1.) The given array contains fewer than two elements,
or...
// 2.) All elements of the array are equal to each other.
// As a hint, you only need to compare the first element
// to all subsequent elements for this check.
//
// TODO - define your code below this comment
//
// DO NOT MODIFY parseStrings!
public static boolean allEqual(int[] arr){
if (arr.length<=1){
return true;
}
else{
for (int x = 1; x < arr.length; x++) {
if(arr[0] != arr[x]){
return false;
}
}
return true;
}
}
public static int[] parseStrings(String[] strings) {
int[] retval = new int[strings.length];
for (int x = 0; x < strings.length; x++) {
retval[x] = Integer.parseInt(strings[x]);
}
return retval;
}
// DO NOT MODIFY main!
public static void main(String[] args) {
int[] argsAsInts = parseStrings(args);
boolean areEqual = allEqual(argsAsInts);
System.out.println("Are equal: " + areEqual);
}
}
Test output screenshots: