Answer to Question #186651 in Java | JSP | JSF for Syed kaif ali

Question #186651

Create a class name FunWithArrays and create the following methods:

⦁ consecutiveValueChecker(int arr[]): This method will not allow user to input consecutive values in an array

Input:

3,4,2,1,5,5

Output: 

Cannot input consecutive value please input value other than 5

⦁ calcultesLongestSequence(String arr[]): This method will take a string array and calculate length of values at each index also print the word having the longest length


1
Expert's answer
2021-04-28T07:43:19-0400
import java.util.Arrays;
import java.util.Scanner;


public class FunWithArrays {
	/**
	 * This method will not allow user to input consecutive values in an array
	 * @param arr
	 */
	public boolean consecutiveValueChecker(int arr[]) {
		Arrays.sort(arr);
		for(int i=0;i<arr.length-1;i++){
			if((arr[i+1]-arr[i])!=1) {				
				System.out.print("\nCannot input consecutive value please input value other than "+arr[i+1]+"\n");
				return false;
			}
		}
		return true;
	}
	/**
	 * This method will take a string array and calculate length of values at each index also print the word having the longest length
	 * @param arr
	 */
	public void calcultesLongestSequence(String arr[]) {
		int wordHavingLongestLength=arr[0].length();
		String word=arr[0];
		System.out.println();
		for(int i=0;i<arr.length;i++){
			System.out.println("The length of word \""+arr[i]+"\" is "+arr[i].length());
			if(wordHavingLongestLength<arr[i].length()) {
				wordHavingLongestLength=arr[i].length();
				word=arr[i];
			}
		} 
		System.out.println("\nThe word having the longest length is \""+word+"\"\n");
	}
	
	/**
	 * Main method
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner input =new Scanner(System.in);
		FunWithArrays funWithArrays=new FunWithArrays();
		//read comma-separated values
		System.out.print("Enter comma-separated values, example(3,4,2,1,5,5): ");
		String values[]=input.nextLine().split(",");
		int numbers[]=new int[values.length];
		for(int i=0;i<values.length;i++) {
			numbers[i]=Integer.parseInt(values[i]);
		}
		if(funWithArrays.consecutiveValueChecker(numbers)) {
			System.out.print("\nArray elements are consecutive\n");
		}
		
		//read  space-separated word
		System.out.print("\nEnter space-separated word, example(It is a simple string): ");
		values=input.nextLine().split(" ");
		funWithArrays.calcultesLongestSequence(values);
		
		input.close();
		
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS