简体   繁体   中英

Write a method to print out a string “Name” multiple times

I am answering a question for an Intro to Programming class and cannot - after reading through my notes, Big Java book, and looking online - find out where to begin.

It seems as though it should be very simple, but I just need to get started. All of this is for Java and is being worked on in Eclipse.

The task is to take in a name ("Name") and a number (int x) and display the "Name" x number of times on one line, x-1 times on another line, and so on and so on until you display the name only once. It seems like it should be a reverse accumulator, but I'm having trouble starting my method. How do I begin? I know I can't multiply strings in Java like you can in python or other languages, but how can I print the "Name" x number of times without building an Array or inputing

System.out.println("name" + " " + "name" + " "...).

Any suggestions are appreciated. I am a novice at this. Thank you!

You need a loop , a common feature of programming languages.

Have a close look at the java for loop.

Additional hint:

System.out.println("test") prints it's argument in a single line while System.out.print("test") doesn't add a CR/LF after test .

You should read about java flow control statements . The for and while constructs would allow you to do what you want.

You can do this by using System.out.print and System.out.println .

Here is the sample code: (not the actual code which you want, just a SAMPLE)

import java.io.*;

public class StringNameTest
{
    public static void main(String args[])
    {
            String strNumber = "";
            String strName = "";
            int intNumber;
            try 
            {
                //  open up standard input
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                //  prompt the user to enter their name
                System.out.print("Enter your name: ");
                strName = br.readLine();

                System.out.print("Enter the number of times you want to print your name: ");
                strNumber = br.readLine();
                intNumber = Integer.parse(strNumber);

                for (row = 0; row < intNumber; row++)
                {
                    for(col = 0; col < intNumber; col++)
                        System.out.print(strName + " ");

                    System.out.println("");
                }
            } 
            catch (Exception ex) {
                System.out.println(ex.getMessage());
                System.exit(1);
            }


    }
}

Hope this helps.

Your method gets a string with the name and a count. Using one for loop to count and another to repeat the name value, you should be able to get the output you're after.

System.out is a printstream and it has both println() to output a line ended with a linebreak and print() to output a string without ending it with a linebreak.

public class test{

    public static void main(String[] args){

        int i = 0;
        int j = 20;

   for(i = 1; i <= j; i++){

          System.out.println("My Name");


   } //ends for loop

     // use system.out.print("") for same line 


}    //ends static void main

}
int x;
int y = 1;

x = scanner.nextInt();

for (int i = 1; i <= x; i++) {
    for (int j = 1; j <= y; j++) {
        System.out.print("O");
    }
    System.out.println();
    ++y;
}
public class WithoutLoop
{
      static int count;
   public static void repeat(String s)
   {
       while(count <= 10)
       {
           System.out.println(s);
           count++;
       }
   }
   public static void main(String[] args)
   {
        repeat("hello");
   }
}

Use an outer loop that counts to x and an inner loop that counts to (x - outer loop counter). Be aware of the common "one off" error.

It is correct that Java doesn't have built-in String repetition. But you can define your own method that does exactly this.

public static String repeated(String s, int times) {
  StringBuilder sb = new StringBuilder();
  // TODO: append /s/ to /sb/ for /times/ times.
  return sb.toString();
}

Good point for you that you want to use this "operator" instead of putting together everything into one large block of code. This helps to keep your programs readable.

First thought: you need n lines. So, enter a loop.

for (int i = 0; i < n; ++i)
{

Then: you need to print on line i the string n - i times. Enter a nested loop:

     for (int j = 0; j < n - i; ++j)
     {

Then start off printing the name:

           System.out.print(name + " ");
     }

Notice I didn't use println , because we want all the names on the same line.
Now you need to end the line when we printed n - i times:

     System.out.println();

Close our outer-loop:

}

And if you don't know how to make the program ask the name and the integer n to the user:

String name = null;
int n = 0;
try
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the name: ");
    name = br.readLine();
    System.out.print("How many times (n): ");
    n = Integer.parseInt(br.readLine());
} catch (Exception e)
{
    e.printStackTrace();
    System.exit(-1); // exit!, there was an error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM