Need to write a java program from pseudo code, I’ve got a bit of code written, its not working and I’m not sure if i’ve done it right or not as I simply tried to follow the pseudo code –
- Read i
- While i > 0
- Print the remainder i % 2
-
Set i to i / 2
import java.util.Scanner; import java.util.Scanner; public class InputLoop { public static void main(String[] args) { int i = 0; Scanner scan = new Scanner(System.in); System.out.println("Enter an integer"); while (!scan.hasNextInt()) // while non-integers are present { scan.next(); System.out.println ("Bad input. Enter an integer."); } while (i>0) // while greater than 0 { int input = scan.nextInt(); System.out.println (i%2); i = (i/2); } } }
Frankly speaking, you
didn't(Ah missed it earlier) exactly followed the pseudo-code. The pseudo code tells you toread i, whereas you are readinginput. That’s one problem.Second problem is that, you should read the input outside the
whileloop where you are doing the processing with the input. That is the 2nd thing you didn’t followed.Currently your while loop is: –
This is read
inputfrom user on every iteration which you don’t want.So, you need to modify your code a little bit: –