views:

541

answers:

6

Hi Guys, 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

+3  A: 

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.

jkff
If efficiency is a concern, then you should definitely note that any kind of concatenation is unnecessary to solve this problem. Only Omega(lg n) memory is necessary.
+2  A: 

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);
erickson
+1  A: 

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.

A: 

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);
Paul Clapham
A: 

Hahaha lekker Tom;) Ik kom er ook niet uit..pff. Ist jou al gelukt? Wrom ben j nu dan niet bij practicum..:p xx

Sharonne