Java Programming In this lab students continue to write programs using multiple
ID: 3804255 • Letter: J
Question
Java Programming
In this lab students continue to write programs using multiple classes. By the end of this lab, students should be able to
Write classes that use arrays and ArrayLists of objects as instance variables
Write methods that process arrays and ArrayLists of objects
Write getter and setter methods for instance variables
Write methods using object parameters and primitive types
Question-
class StringSet. A StringSet object is given a series of up to 10 String objects. It stores these Strings (or a reference to them, to be precise) and can perform limited calculations on the entire series.
The StringSet class has the following specification:
Explanation / Answer
import java.io.*;
import java.util.Scanner;
class StringSet
{
private String []strList;
private int strCount;
public StringSet()
{
strList = new String[10];
strCount = 0;
}
public void add(String newStr)
{
if(strCount == 10){
System.out.println("List full. Cannot insert more string");
return;
}
strList[strCount] = newStr;
strCount++;
}
public int size()
{
return strCount;
}
public int numChar()
{
int i=0;
int length = 0;
for(;i<strCount;i++)
{
length += strList[i].length();
}
return length;
}
public int countStrings(int len)
{
int i=0;
int count = 0;
for(;i< strCount;i++)
{
if(strList[i].length() == len)
{
count++;
}
}
return count;
}
}
public class StringSetTester
{
public static void main(String []args)
{
int numStr = 0, i=0;
Scanner in = new Scanner(System.in);
StringSet list = new StringSet();
System.out.print("How many strings will you enter? ");
numStr = in.nextInt();
in.nextLine();
for(;i < numStr ;i++)
{
System.out.println("Enter String " + (i+1));
list.add(in.nextLine());
}
System.out.println("Number of string in the list : " + list.size());
System.out.println("Number of characters in the list : " + list.numChar());
System.out.println("Number of strings having 5 characters : " + list.countStrings(5));
System.out.println("Number of strings having 7 characters : " + list.countStrings(7));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.