java - Returning the value that for statement prints -


i return information output statement prints.

for instance:

public static int countnumbers(int x) {      (int = 1; <= x; i++) {         system.out.println(i);     }      return something; // should values statements prints.                       // example, countnumbers(5) returns 12345. } 

so when call method somewhere else, output.

so:

int output = countnumbers(3); //output = 123; 

how can done?

use stringbuilder accumulate result. update: convert int using integer.parseint:

public static int countnumbers(int i) {     stringbuilder buf = new stringbuilder();      (int i=1; i<=5; i++) {       buf.append(i);     }     return integer.parseint(buf.tostring()); } 

note works small values of i (up 9), otherwise integer overflow.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -