can anyone help
thanks
Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!
private void sum() { int sum = 0; String s = ""; for( int i = 1;i < 1000;i++ ) { sum += i; s = " " + sum; if( s.indexOf( '7' ) == -1 ) { System.out.print( s ); } }
I would like to point out that constantly rebuilding a String is not a good habit. Strings are immutable. Everytime you append to a String or reset the value of a String, new memory will be allocated for that String. It would be much better to use StringBuffer or StringBuilder (which are mutable classes). In this case, the best way to go about printing out the sum is simply System.out.print(" " + sum);. This saves us a variable, and saves us tons of memory allocation (the way you're doing, memory will be allocated for s 1000 times! [actually 999, but it was fixed in your other post]).try this:
private void sum() { int sum = 0; String s = ""; for( int i = 1;i < 1000;i++ ) { sum += i; s = " " + sum; if( s.indexOf( '7' ) == -1 ) { System.out.print( s ); } }
note: s.indexOf( '7' ) return -1 if '7' is not found
public void sum() { int sum = 0; for (int i = 1; i <= 1000; i++) { sum += i; if (String.valueOf(sum).indexOf('7') == -1) { System.out.print(sum + " "); } } }
Edited by destin, 04 February 2006 - 11:32 AM.
I would like to point out that constantly rebuilding a String is not a good habit.
0 members, 0 guests, 0 anonymous users
Community Forum Software by IP.Board
Licensed to: Geeks to Go, Inc.