Hi I am hoping for a little direction/help on the following task I am struggling with..
Provide two classes which implement the ConsolePrint interface.
• One is called SimplePrint and it will just print the supplied argument directly to the console.
e.g. simplePrintObject.printInfo(“Heading this is not fancy”); would output:
Heading this is not fancy
• One is called FancyPrint. It should use StringTokenizer or String.split() to break up the string.
The first part of the string should be treated as a header and the other parts should be separated by tabs in the output.
e.g. fancyPrintObject.printInfo(“Heading this is quite fancy”); would output:
*********** Heading **********
this is quite fancy
******************************
Note: You should aim to have both “starred” rows take up the same width, regardless of the size of the header (for example, you can assume that the maximum length of the header string is 20 and that the first and last rows will output 30 characters – which will be 30 * in the case of the last row.)
Provide a basic class called ConsolePrintTest which will test each of the two classes. Make sure that your classes can handle empty strings and null strings.
So far I have written my interface as directed:
public interface ConsolePrint
{
void printInfo(String infoToPrint);
}
And a small program using the Split.split method..
public class PrintTester {
public static void main(String args[]) {
String str = new String("\n\n**************Heading************** \n\n\t" +
"This Is Quite Fancy\n" +
"\n***********************************");
for (String retval: str.split(" ", 1)) {
System.out.println(retval);
}
}
}
But trying to implement the ConsolePrint interface as directed in two classes has me stumped after days of reading and searching!
Read it literally: You have to write two classes.
public class SimplePrint implements ConsolePrint {
public void printInfo(String infoToPrint) {
// method implementation here
}
}
public class FancyPrint implements ConsolePrint {
public void printInfo(String infoToPrint) {
// method implementation here
}
}
and a test driver:
public class ConsolePrintTest {
public static void main(String [] args) {
ConsolePrint printer = null;
// figure out how to instantiate different types.
for (String arg : args) {
printer.printInfo(arg);
}
}
}
Related
is it possible to create a class and have a String ... attribute that takes as many or as little strings as you put?
example:
please excuse my rough pseudocode, this is for java.
//this is the method:
public void getXXXX(String ...) {
//random code executes in a loop with as many as strings that are inputted
}
//this code calls it
getXXXX("Benjamin","Jordan","Steve")
getXXXX("Pengu","No")
getXXXX("hi")
Yes, what you entered will more or less work, you just need a parameter name after your type.
class StringDecorator {
public static String join(final String... strings) {
final var builder = new StringBuilder();
for (final var string : strings) {
builder.append(string);
}
return builder.toString();
}
}
Then invoke this somewhere
StringDecorator.join("Hello, ", "World!"); // "Hello, World!"
Still learning the basics however I've been stuck on this. I'm trying to add members to a club from the methods I've wrote, but I'm getting an error on the join method..
import java.util.ArrayList;
public class Club
{
private ArrayList<String> memberList;
public Club()
{
memberList = new ArrayList<String>();
}
public void join(String newMember)
{
memberList.add(newMember);
}
}
public class TestClub
{
public TestClub()
{
}
public static void main(String args[]){
Club myClub = new Club();
System.out.println("The club has " +
myClub.numberOfMembers() +
" members.");
myClub.join("Gary", 5, 2019));
}
}
I know I'm missing something, just can't figure out what. I create the club object but it won't let me add to the list. How do I get the object to accept 3 values/arguments?
This line:
myClub.join("Gary", 5, 2019));
You have two closing parentheses. You might want to delete the last one. Also, you have 3 variables, the string, the integer and another integer.
Maybe you want to say:
myClub.join("Gary");
or
myClub.join("Gary, 5, 2019");
Also, you haven't yet implemented the method, numberOfMembers in the Club class, so that will always fail.
myClub.numberOfMembers()
You would need to have a method in Club class that returns the number of members, meaning the memberList size.
1)You have added extra closing ')' also method 'join(String newMember)' has one parameter, the String. You are trying to pass it 3 value :- join("Gary", 5, 2019);
2) Also your arrayList is of type String you can only add String values eg : "Gary" and not Integer eg : 5 or 2019.
You can also redefine method 'joins' like below for adding multiple value in single method call
public void join(String ...newMember)
{
Collections.addAll(memberList, newMember);
}
and change method call as below
myClub.join("Gary", "5", "2019");
Create a class StringDemo that contains the following static methods:
• A method that takes in a sentence, tokenises it using a single space, and then prints only the words that start with “pre”.
• The main method where you declare 2 variables and initialise them to sentences of your choice; then test the method that you have defined in previous step using the 2 sentences.
My attempt
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car
seats";
String S2 = "I have a lovely designed car that has many car features
beautifully and the car has a good car";
printWordsWithPre(S1);
printWordsWithPre(S2);
System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));
}
//- Tokenises a string/sentence and prints only the words that end with
ly.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
if(sTokens[i].endsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
Try the following code:
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car seats";
String S2 = "I have a lovely designed car that has many beautifully predesigned car features and the car has a good prebuilt car";
printWordsWithPre(S1);
printWordsWithPre(S2);
// These functions don't return any data so they can't be printed. The results are already printed in the function above.
/*System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));*/
}
// Tokenises a string/sentence and prints only the words that starts with pre.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
//check if it starts with rather than ends with
if(sTokens[i].startsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
}
I've made the following changes:
Added a few words starting with pre;
Removed the System.out.println's
in main because they tried to print a void return;
changed endsWith
to startsWith.
You used endsWith instead of startsWith
We recently started learning about static methods and for this assignment we are making a "String Helper" program that creates a few static methods that modify strings, and this is the task for one of them:
meshStrings: This method takes in two strings via parameters, meshes them together, and returns the meshed strings. Meshing alternates the each character in the first string with every character in the next string. If there are not enough characters to fully mesh then the rest will be appended to the end. For instance if the two strings were "harp" and "fiddle" the returned string will be hfairdpdle.
Here's the start of what I have, I don't have much:
public class StringHelper {
public static String meshStrings (String string1, String string2)
{
}
Driver class:
public class StringHelperTester {
public static void main (String[] args)
{
System.out.print(StringHelper.meshStrings("fiddle", "harp"));
}
I assume you'll have some type of for loop that prints out the charAt length of each string but I'm not exactly sure the best way to set it up. Help is appreciated.
the best way to enchance your skills is to just try ...
public static String meshStrings (String string1, String string2) {
StringBuffer buff = new StringBuffer();
int max = Math.max(string1.length(), string2.length());
for(int i = 0; i < max; i++) {
if(i < string1.length()) {
buff.append(string1.charAt(i));
}
if(i < string2.length()) {
buff.append(string2.charAt(i));
}
}
return buff.toString();
}
KISS : keep it simple and stupid. then you can enhance this code if you want, it's not optimal.
I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!