• Java, Infinite Loop Issue
    3 replies, posted
Hello Facepunch, I'm new to Java, and I'm trying to get this program to work, but it keeps crashing due to an infinite loop that I have no idea how to fix. Here's the question... [B]When The user enters the exponent at a promtp, the program displays 2 to that power. The program halts when the user enters -1[/B] Here's what I have so far.... [CODE]import java.util.Scanner; public class Power{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); System.out.print("Enter the exponent that will display 2 to that power: " ); int x; x = reader.nextInt(); int y = -1; while ( x > 0 ){ System.out.println(Math.pow(2, x)); } System.out.println( +x ); } }[/CODE] The problem here is an infinite loop.... Please and Thank You
you need to update x in the loop try this: [code] import java.util.Scanner; public class Power { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter the exponent that will display 2 to that power: "); int x = reader.nextInt(); while(x != -1) { System.out.println(Math.pow(2, x)); x = reader.nextInt(); } } } [/code]
[QUOTE=NovembrDobby;19771479]you need to update x in the loop try this: [/QUOTE] Thank You very much, Now I Just have to figure out how to make the program halt when the user enters -1 EDIT: Never mind, it seems you already did that for me, Thank you again. Now, I'm going to try and make it so the user can enter any base they want
it does already ;p
Sorry, you need to Log In to post a reply to this thread.