Tuesday, July 28, 2009

Java for loop help?

I am making a new question b/c i didnt specify that i was using java. ur supposed to take the inetger that the user inputs and use a for loop so it starts from 2 keeps adding until it get to the intege rinputed. for example if the user inputs 5, the program should print out 14. (2+3+4+5) how would u write that using for loop? thanks in advance.





here is what i have so far





import java.util.Scanner;


public class Basic {





public static void main(String[] args) {


// Create application frame.


BasicFrame frame = new BasicFrame();


Scanner input = new Scanner(System.in);


int x;








System.out.print("Enter a number: ");


x = input.nextInt();





for (int i = 2; i %26lt;= x; i++)


{


System.out.println(i);





}

Java for loop help?
Replace your for loop with this:





int j = 0;


for (int i = 2; i %26lt;= x; i++)


{


j+=i;


}


System.out.println("" + j);








(appending an int to a blank string is a good way to make it play nice, since ints don't have toStrings)





Two other things you should be aware of:





* if your Scanner doesn't find an int, it may throw an exception.


* if someone inputs an integer less then 2, it'll never finish (since starting with two and adding one each time will never get to that number). you'll get an integer overflow (where the number keeps growing until it's too big to fit into an integer's space)
Reply:int sum = 0;





for (int i = 2; i %26lt;= x; i++ ) {


if ( i != 2 ) {


System.out.print(" + ");


}


System.out.print(i);


sum += i;


}





System.out.println(" = " + sum);


No comments:

Post a Comment