Question

In: Computer Science

import java.util.Scanner; import java.util.Arrays; /* You have 3 small methods to write for this exam; public...

import java.util.Scanner;
import java.util.Arrays;

/*
You have 3 small methods to write for this exam;
public static int smallest(int[] v1, int[] v2)
public static int[] convert1(String str)
public static String convert2(int[] v)
  
The comments right before each of them tell you exactly what they are
expected to do. Read all requirements first, then start implementing
the easiest methods first. You may work on them in any order.

You are also provided with a main method and two other methods that
are just there to call the methods your wrote with a bunch of tests
and display the outcomes of these tests on the console to help you debug
them.

Please note that the tests we provide you with are not exhaustive.
Your methods still need to meet all requirements even if we did
not provide you with a test for that particular requirement.

if you want to add more tests, I recommend you modify the main method.
If you are comfortable with the code in the two testing methods,
you may also modify them instead but do not waste too much time working
on them.

Good luck!   
*/
public class COP2513E1{

/**
This method returns 1 if vector v1 is the "smallest", 2 if it is vector v2,
or 0 otherwise.
We define "smallest" as follows;
If one of the vector has fewer elements than the other, it is the smallest one.
If both are the same size, then we look at every element one by one in order.
As soon as one of the two vectors has an element that is < than the corresponding
element from the other vector, then it is recognized as the "smallest" one by our method.
**/
public static int smallest(int[] v1, int[] v2){
return 0; // always returns 0 for now, replace this with your code
}// end method smallest




/**
This method takes a string that is guaranteed to be made only
of digits, without spaces or anything else.
Examples; "123" or "0"
Your goal is to create a new array of int values that will hold
each of the digits specified in the String.
Example; if the string passed is "123" your returned array
should contain the int value 1 at index 0, the value 2 at index 1,
and the value 3 at index 2.
Once you are done, return the reference to your newly created
array of int values.
**/
public static int[] convert1(String str){
return new int[1]; // always returns an array with 1 element for now, replace this with your code
}// end method convert1


/**
This method does the opposite work of the above convert1 method.
It takes a vector of single-digit int values and return a string
with all these digits one after the other.
If one of the values in the vector is not in the range 0 to 9 inclusive,
then simply have this method return an empty string as result instead.
**/
public static String convert2(int[] v){
return ""; // always returns an empty string for now, replace this with your code
}// end method convert2



/*
Do not modify the main, or the other methods below this line,
except if you want to add more tests
*/
//=========================================================================


public static void main(String[] args){
testSmallest();
testConvert();
}// end main method
  
public static void testSmallest(){
System.out.println("Testing your method smallest(...)");
  
int[][] testVectors1 = {
{1,2,3},
{1,2,3,4},
{1,2,3},
{1,2,3},
{2,3,4}
};
  
int [][] testVectors2 = {
{1,2,3,4},
{1,2,3},
{1,2,3},
{2,3,4},
{1,2,3}   
};
  
int [] expectedOutcomes = {
1, 2, 0, 1, 2
};
  
if((expectedOutcomes.length != testVectors2.length)
||(expectedOutcomes.length != testVectors1.length)
||(testVectors1.length != testVectors2.length)){
System.out.println("All tables must have the same # of tests");
System.exit(-1);
}// end if
  
int nTests = expectedOutcomes.length;
  
for(int test=0; test < nTests ; test++){
int observedOutcome = smallest(testVectors1[test], testVectors2[test]);
System.out.print("\tTest #" + test + " with vectors "
+ Arrays.toString(testVectors1[test]) + " and " + Arrays.toString(testVectors2[test]));
if(observedOutcome == expectedOutcomes[test])
System.out.println(" SUCCEEDED");
else
System.out.println(" FAILED");
}// end for loop
} // end testSmallest method


public static void testConvert(){
String[] strings= {
"",
"0",
"9",
"12",
"123"
};
  
int[][] vectors = {
{},
{0},
{9},
{1,2},
{1,2,3}
};
  
System.out.println("\nTesting your method convert1(...)");
if(vectors.length != strings.length){
System.out.println("All tables must have the same # of tests");
System.exit(-1);
}// end if
  
for(int test=0 ; test < strings.length ; test++){
int[] observed = convert1(strings[test]);
System.out.print("\tTest #" + test + " with string \"" + strings[test] + "\"");
System.out.println(" "+ (Arrays.equals(observed, vectors[test])?"SUCCEEDED":"FAILED"));
}//end for loop
  
System.out.println("\nTesting your method convert2(...)");

for(int test=0 ; test < vectors.length ; test++){
String observed = convert2(vectors[test]);
System.out.print("\tTest #" + test + " with vector " + Arrays.toString(vectors[test]));
System.out.println(" "+ (observed.equals(strings[test])?"SUCCEEDED":"FAILED"));
}//end for loop

}// end testConvert method

} // end class

Solutions

Expert Solution

import java.util.Scanner;
import java.util.Arrays;

/*
You have 3 small methods to write for this exam;
public static int smallest(int[] v1, int[] v2)
public static int[] convert1(String str)
public static String convert2(int[] v)
  
The comments right before each of them tell you exactly what they are
expected to do. Read all requirements first, then start implementing
the easiest methods first. You may work on them in any order.

You are also provided with a main method and two other methods that
are just there to call the methods your wrote with a bunch of tests
and display the outcomes of these tests on the console to help you debug
them.

Please note that the tests we provide you with are not exhaustive.
Your methods still need to meet all requirements even if we did
not provide you with a test for that particular requirement.

if you want to add more tests, I recommend you modify the main method.
If you are comfortable with the code in the two testing methods,
you may also modify them instead but do not waste too much time working
on them.

Good luck!   
*/
public class COP2513E1 {

        /**
         * This method returns 1 if vector v1 is the "smallest", 2 if it is vector v2,
         * or 0 otherwise. We define "smallest" as follows; If one of the vector has
         * fewer elements than the other, it is the smallest one. If both are the same
         * size, then we look at every element one by one in order. As soon as one of
         * the two vectors has an element that is < than the corresponding element from
         * the other vector, then it is recognized as the "smallest" one by our method.
         **/
        public static int smallest(int[] v1, int[] v2) {
                
                if(v1.length < v2.length) {
                        return 1;
                } else if(v1.length > v2.length) {
                        return 2;
                } else {
                        
                        for(int i=0; i<v1.length; i++) {
                                
                                if(v1[i] < v2[i]) {
                                        return 1;
                                } else if(v1[i] > v2[i]) {
                                        return 2;
                                }
                                
                        }
                        
                }
                
                return 0; // always returns 0 for now, replace this with your code
        }// end method smallest

        /**
         * This method takes a string that is guaranteed to be made only of digits,
         * without spaces or anything else. Examples; "123" or "0" Your goal is to
         * create a new array of int values that will hold each of the digits specified
         * in the String. Example; if the string passed is "123" your returned array
         * should contain the int value 1 at index 0, the value 2 at index 1, and the
         * value 3 at index 2. Once you are done, return the reference to your newly
         * created array of int values.
         **/
        public static int[] convert1(String str) {
                
                int result[] = new int[str.length()];
                
                for(int i=0; i<str.length(); i++) {
                        result[i] = str.charAt(i) - '0';
                }
                
                return result; // always returns an array with 1 element for now, replace this with your code
        }// end method convert1

        /**
         * This method does the opposite work of the above convert1 method. It takes a
         * vector of single-digit int values and return a string with all these digits
         * one after the other. If one of the values in the vector is not in the range 0
         * to 9 inclusive, then simply have this method return an empty string as result
         * instead.
         **/
        public static String convert2(int[] v) {
                
                String s = "";
                for(int x: v) {
                        if(x < 0 || x > 9) {
                                return "";
                        }
                        s += x;
                }
                
                return s; // always returns an empty string for now, replace this with your code
        }// end method convert2

        /*
         * Do not modify the main, or the other methods below this line, except if you
         * want to add more tests
         */
//=========================================================================

        public static void main(String[] args) {
                testSmallest();
                testConvert();
        }// end main method

        public static void testSmallest() {
                System.out.println("Testing your method smallest(...)");

                int[][] testVectors1 = { { 1, 2, 3 }, { 1, 2, 3, 4 }, { 1, 2, 3 }, { 1, 2, 3 }, { 2, 3, 4 } };

                int[][] testVectors2 = { { 1, 2, 3, 4 }, { 1, 2, 3 }, { 1, 2, 3 }, { 2, 3, 4 }, { 1, 2, 3 } };

                int[] expectedOutcomes = { 1, 2, 0, 1, 2 };

                if ((expectedOutcomes.length != testVectors2.length) || (expectedOutcomes.length != testVectors1.length)
                                || (testVectors1.length != testVectors2.length)) {
                        System.out.println("All tables must have the same # of tests");
                        System.exit(-1);
                } // end if

                int nTests = expectedOutcomes.length;

                for (int test = 0; test < nTests; test++) {
                        int observedOutcome = smallest(testVectors1[test], testVectors2[test]);
                        System.out.print("\tTest #" + test + " with vectors " + Arrays.toString(testVectors1[test]) + " and "
                                        + Arrays.toString(testVectors2[test]));
                        if (observedOutcome == expectedOutcomes[test])
                                System.out.println(" SUCCEEDED");
                        else
                                System.out.println(" FAILED");
                } // end for loop
        } // end testSmallest method

        public static void testConvert() {
                String[] strings = { "", "0", "9", "12", "123" };

                int[][] vectors = { {}, { 0 }, { 9 }, { 1, 2 }, { 1, 2, 3 } };

                System.out.println("\nTesting your method convert1(...)");
                if (vectors.length != strings.length) {
                        System.out.println("All tables must have the same # of tests");
                        System.exit(-1);
                } // end if

                for (int test = 0; test < strings.length; test++) {
                        int[] observed = convert1(strings[test]);
                        System.out.print("\tTest #" + test + " with string \"" + strings[test] + "\"");
                        System.out.println(" " + (Arrays.equals(observed, vectors[test]) ? "SUCCEEDED" : "FAILED"));
                } // end for loop

                System.out.println("\nTesting your method convert2(...)");

                for (int test = 0; test < vectors.length; test++) {
                        String observed = convert2(vectors[test]);
                        System.out.print("\tTest #" + test + " with vector " + Arrays.toString(vectors[test]));
                        System.out.println(" " + (observed.equals(strings[test]) ? "SUCCEEDED" : "FAILED"));
                } // end for loop

        }// end testConvert method

} // end class
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

import java.util.Scanner; public class MonthsOnAndAfter { // You will need to write a method that makes...
import java.util.Scanner; public class MonthsOnAndAfter { // You will need to write a method that makes this // code compile and produce the correct output. // YOU MUST USE switch! // As a hint, you should not have to use the name of each // month more than once. // TODO - write your code below this comment. // DO NOT MODIFY main! public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter month (0-11): "); int month...
import java.util.Scanner; public class Months { // You will need to write a method that makes...
import java.util.Scanner; public class Months { // You will need to write a method that makes this // code compile and produce the correct output. // YOU MUST USE switch! // TODO - write your code below this comment. // DO NOT MODIFY main! public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter month (0-11): "); int month = input.nextInt(); String output = monthAsString(month); System.out.println(output); } }
import java.util.Scanner; public class LetterGrade { // The method you write will return a String representing...
import java.util.Scanner; public class LetterGrade { // The method you write will return a String representing a letter // grade (e.g., "A", "A-", "B+", etc.). // The letter grade is determined by the given percentage, according // to the scale specified on page 2 of the class syllabus (available // here: https://kyledewey.github.io/comp110-spring18/syllabus.pdf). // You may assume that the given percentage is between 0.0 and 100.0 // TODO - write your code below this comment.    public static String letterGrade(double percentage){...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following:...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following: // // 1.) Define a private instance variable which can // hold a reference to a Random object. // // 2.) Define a constructor which takes a seed value. // This seed will be used to initialize the // aforementioned Random instance variable. // // 3.) Define a static method named numberToDirection // which takes a direction number and returns a String // representing...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
Write program in Java import java.util.Scanner; public class Lab7Program { public static void main(String[] args) {...
Write program in Java import java.util.Scanner; public class Lab7Program { public static void main(String[] args) { //1. Create a double array that can hold 10 values    //2. Invoke the outputArray method, the double array is the actual argument. //4. Initialize all array elements using random floating point numbers between 1.0 and 5.0, inclusive    //5. Invoke the outputArray method to display the contents of the array    //6. Set last element of the array with the value 5.5, use...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r =...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r = new Random(seed); }    public static String numberToDirection(int a){ if(a==0) return "North";    if(a==1) return "NorthEast"; if(a==2) return "East"; if(a==3) return "Southeast"; if(a==4) return "South"; if(a==5) return "Southwest"; if(a==6) return "West";    if(a==7) return "Northwest";    return "Invalid Direction" ; } public String randomDirection(){ return numberToDirection(r.nextInt()% 4 + 1); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter seed: ");...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME =...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class BowlerReader { private static final String FILE_NAME = "bowler.txt"; public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading Data from file"); Scanner fileReader = new Scanner(new File(FILE_NAME)); System.out.printf("%-20s%-10s%-10s%-10s%-10s\n", "Sample Data", "Game 1", "Game 2", "Game 3", "Average"); int bowler = 1; while (fileReader.hasNext()) { String scores[] = fileReader.nextLine().split("\\s+"); double average = Integer.parseInt(scores[0]) + Integer.parseInt(scores[1]) + Integer.parseInt(scores[2]); average /= 3; System.out.printf("%-20s%-10s%-10s%-10s%-10.2f\n", "Bowler " + bowler, scores[0], scores[1], scores[2], average); bowler += 1; }...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT