0% found this document useful (0 votes)
14 views4 pages

Java Array and Nucleotide Exercises

The document contains 3 Java exercises that demonstrate the use of arrays. Exercise 1 declares and initializes different array types including strings, integers, and planets. Exercise 2 includes a Bollywood names array, searches for a name, sorts the array, and prints the sorted values. It also declares and sorts an integer ages array. Exercise 3 uses a while loop to input nucleotide values, uses a switch statement to check the input and print the nucleotide type, and concatenates the values into a DNA sequence that is printed at the end.

Uploaded by

Andrew Lassia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Java Array and Nucleotide Exercises

The document contains 3 Java exercises that demonstrate the use of arrays. Exercise 1 declares and initializes different array types including strings, integers, and planets. Exercise 2 includes a Bollywood names array, searches for a name, sorts the array, and prints the sorted values. It also declares and sorts an integer ages array. Exercise 3 uses a while loop to input nucleotide values, uses a switch statement to check the input and print the nucleotide type, and concatenates the values into a DNA sequence that is printed at the end.

Uploaded by

Andrew Lassia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Assignment

Exercise 1
[Link]
// class ArrayDecs
public class ArrayDecs {

//main clasS
public static void main(String[] args) {
// TODO Auto-generated method stub
// declare cityPopulation with 20 elements
String cityPopulation[]= new String[20];
// declare array squad
String squad[]= new String[11];
//declare array planets and initialize all the planets
String planets[]= {"Mercury", "Venus", "Earth", "Mars", "Jupiter",
"Saturn", "Uranus", "Neptune", "Pluto"
};

Exercise 2
[Link]

import [Link];

public class MyArrays {

public static void main(String[] args) {


// TODO Auto-generated method stub
// declares Bollywood array and initializes with 5 names
String[] Bollywood = new String[]{"Salman", "Aditya", "Arjun","Kapoor",
"Khan"};

//loops through Bollywood array


for(int i=0; i < [Link]; i++)
{
//access each element in array and prints in a seperate line
[Link](Bollywood[i]);
}
//initializes search to Aditya
String search = "Aditya";
boolean isFound = false;
//for loop to iterate through Bollywood array to find each element
for(int i=0; i < [Link]; i++)
{
//compares the element with the seacrh initialized
if([Link](Bollywood[i]))
{
isFound = true;
[Link]("String found at "+(i+1));
}
}
if(!isFound)
{
[Link]("String not found");
}

// Array is sorted
[Link](Bollywood);
[Link]("After sorting names the String array");
for(int i=0; i < [Link]; i++)
{
//prints elements of the array after sorting
[Link](Bollywood[i]);
}
//declares array age and initializes with four integers
int []Ages=new int[]{56,12,32,27};
[Link]("The Integer array");

for(int i=0; i < [Link]; i++)


{
[Link](Ages[i]);
}
// Array is sorted
[Link](Ages);
//prints out sorted ages
[Link]("After sorting the Ages are");
//loops through ages
for(int i=0; i < [Link]; i++)
{
//prints sorted ages
[Link](Ages[i]);
}

}
}

Screenshot

Exercise 3
[Link]
import [Link];
import [Link];
import [Link];
//DNASwitch class
public class DNASwitch {
//main class
public static void main(String[] args) throws IOException {
// inputs from buffer
InputStreamReader read =new InputStreamReader([Link]);
BufferedReader buffer=new BufferedReader(read);
//count loops
int num=0;
String character ="";
while(num<8){//while loops will run 8 times
[Link]("Enter a nucleotide");
char ch=[Link]().charAt(0);
//switch case
switch(ch)
{
case 'a':
case 'A':
//prints Adenine when input is A or a
[Link]("Adenine");
//it is added to the already build string
character+=ch;
break; //break after adding to a string

case 'c':
case 'C':
//prints Cytosine when input is C or c
[Link]("Cytosine");
//it is added to the already build string
character+=ch;
break;//break after adding to a string

case 'g':
case 'G':
//prints Guanine when input is G or g
[Link]("Guanine");
//it is added to the already build string
character+=ch;
break;//break after adding to a string

case 't':
case 'T':
//prints Thymine if input is T or t
[Link]("Thymine");
//it is added to the already build string
character+=ch;
break;//break after adding to a string
//prints invalid when input is incorrect
default:
[Link]("Invalid Nucleotide");
}
num++; //increase counter
}
//output the whole sequense
[Link]("The whole sequence is: "+character);
}
}

Screenshot

Common questions

Powered by AI

The 'main' method acts as the entry point for execution in Java applications. In each class, such as 'ArrayDecs', 'MyArrays', and 'DNASwitch', the 'main' method is where operations begin, including array declarations, user input handling, and conditional logic execution. Its presence is crucial as it defines where and how the program starts running, thus ensuring the java runtime environment knows the starting point of a program execution pipeline .

Loops in the 'MyArrays' class are used extensively for iteration over arrays to perform manipulation tasks such as searching, printing, and sorting. For example, a for-loop iterates through 'Bollywood' to print elements and check if the 'search' string exists, facilitating both data access and validation. Another loop is used after sorting to output sorted array elements. These loops offer structured, repetitive execution paths that are crucial for handling arrays efficiently without manual code repetition for each element, encapsulating both read and write operations .

The 'MyArrays' class employs a linear search with a simple for-loop and a sort using the Arrays.sort() method. Java Streams offer alternative streamlined and functional programming approaches. For searching, Streams can use filter and find operations that provide concise and expressive logic for searching with potential parallel capabilities. Sorting can be handled with Collections.sort(Collections, comparing()), allowing for custom comparators and offering potentially more readable and flexible operations. Streams leverage lambda expressions and parallel processing, which can optimize performance and readability in large data set manipulations versus traditional iterative methods .

The 'DNASwitch' class uses a BufferedReader to take user input, which allows for reading of user data via a command line. The significance of using a switch-case structure is to map user input to specific nucleotide names, such as 'Adenine' for 'A' or 'a', providing an efficient way to handle multiple conditional paths based on input characters. Instead of using multiple if-else statements, switch-case offers a cleaner and more intuitive solution for controlling program flow based on discrete choices .

Relying solely on String arrays in 'ArrayDecs' can lead to increased memory usage because each String is an object and involves more overhead than primitive data types. This might affect runtime performance due to the additional cost of handling object creation, garbage collection, and potentially longer access times during string manipulation tasks. Efficient use involves considering array size limits, opting for char arrays when simpler data forms suffice, and being mindful of memory vs. array element type trade-offs in performance-sensitive applications .

BufferedReader in Java allows for efficient reading of characters, arrays, and lines from an input stream, which is advantageous for processing input from the console as demonstrated in 'DNASwitch'. It handles I/O operations more efficiently compared to Scanner by buffering the input. However, it requires handling IOExceptions and adds complexity in terms of managing input data conversion. Unlike Scanner, BufferedReader alone doesn't support parsing of built-in Java types directly, requiring additional handling to convert input to desired types like integers or floating-point numbers .

Improving error handling in the 'DNASwitch' class could involve enhancing user feedback and managing exceptions. Currently, default case handling prints 'Invalid Nucleotide' for incorrect input. To improve, one could implement exception handling to catch input mismatches or invalid data types using try-catch blocks. Also, prompting users with a clearer instruction message, retry logic upon invalid input, and logging errors for audit purposes would make the program more robust and user-friendly .

The class 'ArrayDecs' demonstrates basic array declarations by showing different ways to define arrays—with explicit sizes for 'cityPopulation' and 'squad', and direct initialization for 'planets'. To enhance understanding for beginners, the class could include comments explaining each declaration type's implications, provide examples of how to populate and manipulate these arrays with data, and demonstrate the use of primitive data types alongside String arrays for comparison .

In 'ArrayDecs', arrays are declared with specific sizes but only 'planets' is initialized with values. 'cityPopulation' and 'squad' are declared with lengths of 20 and 11 without initial values, while 'planets' is initialized with planet names directly during declaration. In 'MyArrays', the arrays 'Bollywood' and 'Ages' are directly declared and initialized with values at the same time, showcasing a more immediate initialization approach. Additionally, operations such as sorting and searching are performed on these arrays, demonstrating different ways to manage and manipulate array data .

In 'MyArrays', a linear search strategy is implemented by iterating over the 'Bollywood' array to find the 'search' term 'Aditya'. The search efficiently identifies and confirms the presence of the term within the array, printing its position. Sorting is performed using the Arrays.sort() method, which arranges both 'Bollywood' and 'Ages' arrays alphabetically and numerically respectively. This approach leverages Java's built-in sorting functionality, which is simple and effective for basic array operations, helping users understand array manipulation through direct examples .

You might also like