开发者

java repeat character [duplicate]

This question already has answers here: 开发者_如何学运维 Simple way to repeat a string (32 answers) Closed 8 months ago.

I am a java beginner, please keep that in mind. I have to make a program that reads a number, and then displays that amount of exclamation mark "!".

This is what i have:

import java.util.Scanner;
import java.io.PrintStream;

class E_HerhaalKarakter1 {

 PrintStream out;

 E_HerhaalKarakter1 () {
  out = new PrintStream(System.out);
 }

 String printUitroeptekens (int aantal) {
  String output = "!"

  for (int i = 0; i <= aantal; i++) {
   output.concat("!");
  }
  return output;
 }

 void start () {
  Scanner in = new Scanner(System.in);

  out.printf("Hoeveel uitroeptekens wilt u weergeven?\n");

  if(in.hasNext()) {
   out.printf("baldbla");
   printUitroeptekens(in.nextInt());
   out.printf("%s",output);
  }
 }

 public static void main (String[] argv) {
  new E_HerhaalKarakter1().start();
 }
}

Thank you


If you do actually have the requirement to create a string which contains X number of exclamation marks, then here's a way to do it without repeated concatenation:

char[] exmarks = new char[aantal];
Arrays.fill(exmarks, '!');
String exmarksString = new String(exmarks);


Your program doesn't work because String.concat() does not change the string, but returns a new string. For example, "a".concat("b") is "ab". So, you should write output = output.concat("!") instead of output.concat("!").

However, this will be very inefficient because building up a string of n exclamation marks will take O(n^2) time (look up "big oh notation" on google or wikipedia, see also Schlemiel the Painter's algorithm).

Look at the documentation to the StringBuilder class and use it. It was designed for building up strings from parts.


It looks like you are very close, Tom.

First, the normal way to build up a String in Java is with the StringBuilder class, like this:

StringBuilder buf = new StringBuilder(aantal);
while (aantal-- > 0)
  buf.append('!');
return buf.toString();

Then, you need to declare a variable named output in the scope of the start() method, and assign the result of the printUitroeptekens() method to that variable, like this:

String output = printUitroeptekens(in.nextInt());
out.printf("%s%n", output);


Your program should have this structure:

read number x 
repeat this x times  
  print '!'

There's nothing in the statement requiring you to actually build a string as far as I can tell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜