Home > Back-end >  How to rewrite method so it prints out the desired outcome for a question?
How to rewrite method so it prints out the desired outcome for a question?

Time:11-06

I have this question I'm trying to finish.

Write a method that receives a String and an integer and then prints the string to the console that many times on the same line, separated by a space, a dash, a star, a dash, and another space.

Sample call:

myMethod("Matthew", 3);

Sample output:

Matthew -*- Matthew -*- Matthew

However, the method I've written doesn't print this output out. I'm new to java. So, help is very much appreciated.

/**
 * 
 */

package myloops;

import java.util.*;

/**
 * @author 
 *
 */
public class Quiz {
    /**
     * 
     * @param name
     * @param num
     */

    public static void myMethod(String name,  int num) {
    
    
    for (int loop = 1; loop <= num; loop   ) {
      if (num%2 != 0) {
         System.out.print("-*-");
       } System.out.print(name);
    }
    }//end of other method
    
    /**
     * @param args
     */
    public static void main(String[] args) {
          
        myMethod("Matthew", 3);
    } // end of main method

} // end of parent class

CodePudding user response:

SO has many examples of answers to similar problems and this one is based on an answer here: https://stackoverflow.com/a/6857936/2711811 ( >= java 8 )

public static void myMethod(String name,  int num) {
    System.out.println(String.join(" -*- ", Collections.nCopies(num, name)));
}

CodePudding user response:

The string *-* must precede every repetition of the name except the first, so you can either print the first on its own and then loop through the rest, or loop through them all and check if it's the first:

public static void myMethod(String name,  int num) {
    for (int loop = 0; loop < num; loop   ) {
        if (loop > 0 ) {
            System.out.print(" -*- ");
        }             
        System.out.print(name);
    }
}

public static void main(String[] args) {      
    myMethod("Matthew", 3);
}

Output: Matthew -*- Matthew -*- Matthew

CodePudding user response:

You have several problems in your code

  1. num is never changed
  2. num%2 != 0 returnning if num is odd and this is not relevent to this problom.

Because you want to print * ufter the word Matthew except the last one you should use the next code:

    for (int loop = 0; loop < num; loop   ) {
        System.out.print(name);
        if (loop != num-1 ) {
            System.out.print(" -*- ");
        }             
    
    }
  • Related