Question

In: Computer Science

This code works fine. In java, can you: change the variable and method names to make...

This code works fine. In java, can you:

change the variable and method names to make logical sense

add method header comments to describe what the method does and what the params/returns are

add a class header comment to describe what the code does

import java.util.Arrays;
import java.util.Scanner;
public class MethodLibrary {
public static void main(String args[]) {
System.out.println("MethodLibrary");

System.out.println("Example use of methods");
int[] smallNums1 = {2, 1, 7, 4, 3};
display("display:", smallNums1);

char [] characters = {'a','b','c','d','e','f'};
first( characters, 2);
System.out.print("after first: ");
System.out.println(characters);

int[] bigNums = {1234, 20001, 3764, 20947, 9099};
System.out.println("after second: " + second(bigNums));

int[] smallNums2 = { 8, 7, 3, 4, 5, 0, 1};
third(smallNums2, true);
System.out.println("after third: " + Arrays.toString(smallNums2));

Scanner i = new Scanner("-5 0 error 25 happy 20 14 end");
int r = fourth( i, "Enter a number between 1 and 20, inclusive", 1, 20);
}

/**
* This method prints the description followed by the contents of list.
* The list begins with '[', ends with ']' and each element is separated
* with ', '.
* Example: display( "a description", new int[]{1,2,3})
* a description [1, 2, 3]
* @param description The text printed out before the list of integers.
* @param list The array of integers to be printed.
*/
public static void display(String description, int[] list) {
System.out.print(description);
System.out.print(" [");
for (int i = 0; i < list.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(list[i]);
}
System.out.println("]");
}

public static void first(char[] r, int b) {
for (int i = 0 ; i < b; i++)
{ char s = r[r.length - 1];
for (int j = r.length - 1; j > 0; j--) {r[j] = r[j - 1]; }
r[0] = s; }
}

public static int second(int[] z) {
int g; g = z[0];
for (int i = 0; i < z.length; i++) { if ( z[i] > g) { g = z[i]; } }
return g;
}

public static void third(int[] t, boolean stl) {
int m;
for (int i = 0; i < t.length; i++) {
for (int j = i + 1; j < t.length; j++) {
if (stl) { if (t[i] > t[j]) { m = t[i]; t[i] = t[j]; t[j] = m;}
} else {if (t[i] < t[j]) {
m = t[i]; t[i] = t[j]; t[j] = m;
}
}
}
}
}

public static int fourth(Scanner a, String b, int c, int d) {
System.out.println(b); boolean v = false; int r = 0;
do {if (a.hasNextInt()) { r = a.nextInt();
if (r >= c && r <= d) { v = true;
} else {System.out.println("Value must be between " + c + " and " + d + ".");
}
} else { a.next(); } } while (!v); return r;
}
}

Solutions

Expert Solution

The requirement of the question was to make code more meaningful to read and assign proper method and variable names to make it more readable. The below code is well commented and names of variables and methods are meaningful and easy to understand

//Code starts here

import java.util.Arrays;
import java.util.Scanner;
//This class has methods for int and char. It has mainly 5 methods : to display number list,move last elements from char list to start, to sort number list, to find greatest number in list and to check if elements in a list lie betweem a given range
public class MethodLibrary {
public static void main(String args[]) {
System.out.println("MethodLibrary");

System.out.println("Example use of methods");
//integer list of small numbers
int[] smallNumbers = {2,1,7,4,3};
//Call display method to print list of numbers
display("Display list: ", smallNumbers);

//list of characters
char[] chars = {'a','b','c','d','e','f'};
  
//Shift last x characters to the starting of array by passing number of characters to be shifted in the second parameter of shiftLastChars method
shiftLastChars(chars, 2);
//Display result returned by shiftLastChars method
System.out.print("After shifting: ");
System.out.println(chars);
  
//integer list of big numbers
int[] bigNumsList = {1234,20001,3764,20947,9099};
  
//Call findGreatest method to find the largest number in the list
System.out.println("Largest number: " + findGreatest(bigNumsList));

//integer list of numbers
int[] sortingList = {8,7,3,4,5,0,1};
//Call sort method to sort the given int array in ascending or descending array based on second parameter true for ascending and false for descending
sort(sortingList, true);
//Display number list after sorting
System.out.println("After sorting: " + Arrays.toString(sortingList));
  
//Get list of values to test if those values lie between 1 and 20
Scanner in = new Scanner("-5 0 error 25 happy 20 14 end");
  
//Call checkRange method to check if values lie between 1 and 20
int result = checkRange(in, "Enter a number between 1 and 20, inclusive", 1, 20);
}

/**
* This method prints the description followed by the contents of list.
* The list begins with '[', ends with ']' and each element is separated
* with ', '.
* Example: display( "a description", new int[]{1,2,3})
* a description [1, 2, 3]
* @param description The text printed out before the list of integers.
* @param list The array of integers to be printed.
*/
public static void display(String description, int[] list) {
System.out.print(description);
System.out.print(" [");
for (int i = 0; i < list.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(list[i]);
}
System.out.println("]");
}

/**
* This method shifts last chars to start of list.
* Move character one by one from last to start of list
* @param list - The given list of characters.
* @param nums - The numbers of characters to be moved from last to
* first.
*/
public static void shiftLastChars(char[] list, int nums) {
for (int i = 0; i < nums; i++) {
//Last char to move
char last = list[list.length - 1];
for (int j = list.length - 1; j > 0; j--) {
list[j] = list[j - 1]; //Move all elements one step towards end and vacate first place
}
list[0] = last; //Move last element to first position
}
}
/**
* This method finds the largest number in a list.
* Compare all numbers and update the greatest if number is largest
* @param list - The given list of integers.
*/
public static int findGreatest(int[] list) {
int greatest;
greatest = list[0];//Initialise greatest with first value in list
for (int i = 0; i < list.length; i++) { //Iterate over list
if (list[i] > greatest) { //If current element in list > greatest , update the greatest with current element value
greatest = list[i];
}
}
return greatest; //return greatest value
}
/**
* This method sorts the list in ascending or descending.
* Based on second parameter sort the list in increasing or decreasing
* order.
* @param list - The given list of integers.
* @param increasing - Sort in increasing if true and decreasing
* if false.
*/
public static void sort(int[] list, boolean increasing) {
int temp; //temp variable to temporary store values
for (int i = 0; i < list.length; i++) { //Iterate over list/array
for (int j = i + 1; j < list.length; j++) {
if (increasing) {
if (list[i] > list[j]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
} else {
if (list[i] < list[j]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
}

/**
* This method checks if values are in a given range
* It has a list and it displays message if value is not in range
* @param list - Scanner has a list of values
* @param description - It tells description of values to enter
* @param start - initial value of range
* @param end - last value of range
*/
public static int checkRange(Scanner list, String description, int start, int end) {
System.out.println(description); //Print description
boolean inRange = false; //True if value in range
int value = 0; //variable to store each value
do {
if (list.hasNextInt()) { //Till list is empty
value = list.nextInt(); //Store list element in value
if (value >= start && value <= end) { //If value in range
inRange = true;
} else {
//Print message if value not in range
System.out.println("Value must be between " + start + " and " + end + ".");
}
} else {
list.next();
}
} while (!inRange); //Repeat until in range
return value; //return value
}
}

//Code ends here


Related Solutions

Hello sir can you plz change my below code like change names , function name and...
Hello sir can you plz change my below code like change names , function name and add comments so it wont look same but run same. change as much as you can thank you. #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<string.h> #include<time.h> struct patient { int id; int age; bool annualClaim; int plan; char name[30]; char contactNum[15]; char address[50]; }; #define MAX_LENGTH 500 struct patient patients[100]; int patientCount = 0; struct claim { int id; int claimedYear; int amountClaimed; int remaininigAmount; }; struct...
Please take this c++ code and make it into java code. /* RecursionPuzzleSolver * ------------ *...
Please take this c++ code and make it into java code. /* RecursionPuzzleSolver * ------------ * This program takes a puzzle board and returns true if the * board is solvable and false otherwise * * Example: board 3 6 4 1 3 4 2 5 3 0 * The goal is to reach the 0. You can move the number of spaces of your * current position in either the positive / negative direction * Solution for this game...
im trying to write a java code that take a matrix of vector and fine it's...
im trying to write a java code that take a matrix of vector and fine it's inverse (the the inverse in linear algebra) then multiple this matrix with a vector to fine other vector (matrix)-1 × ( vector ) = (vector)
how can I change the Gauss-Seidel method to SOR method code in Matlab? The question has...
how can I change the Gauss-Seidel method to SOR method code in Matlab? The question has shows that In implementing SOR method in MATLAB, one should not calculate Tw and cw by formulas Tw = (D -wL)^(-1)[(1-w)D+wU)] and Cw = w(D-wL)^(-1)b , where w stands for omega and using MATLAB's built-in inv function, since this function requires O(n^3) flops and therefore the whole matter loses its point. I have tried for many times but I can't get the correct answers....
please right make it so that it can run on jGRASP and java code please thank...
please right make it so that it can run on jGRASP and java code please thank you Debug Problem 1: As an intern for NASA, you have been instructed to debug a java program that calculates the speed that sound travels in water. Details about the formulas and correct results appear in the comments area at the top of the program Here is the code to debug: importjava.util.Scanner; /**    This program demonstrates a solution to the    The Speed of Sound...
Write a java code snippet to prompt the user for the number of names they’d like...
Write a java code snippet to prompt the user for the number of names they’d like to enter. Create a new array of the size chosen by the user and prompt the user for each of the names. Output the list of names in reverse order.
can you please convert this python code into java? Python code is as shown below: #...
can you please convert this python code into java? Python code is as shown below: # recursive function def row_puzzle_rec(row, pos, visited):    # if the element at the current position is 0 we have reached our goal    if row[pos] == 0:        possible = True    else:        # make a copy of the visited array        visited = visited[:]        # if the element at the current position has been already visited then...
Java code. You will need to make classes that could be used to stage a battle...
Java code. You will need to make classes that could be used to stage a battle as described below. You have been tasked to create a number of items that can be used in an online game. All items can be used on a game character who will have a name, a number of health-points and a bag to hold the items.   Here are examples of items that can be made: Item type of item effectOnHealth other info Widow's Cloak...
assume that the data are stored in variable names x and y. write a matlab code...
assume that the data are stored in variable names x and y. write a matlab code to plot the quadratic spline and along with the data points x= 1 2 3 4 5 6 y= 40 78 125 256 348 425
Code in Java Successive Over-Relaxation (SOR) method.
Code in Java Successive Over-Relaxation (SOR) method.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT