+ 1

Execute a command multiple times with while

Hey guys I want to build a calculator (it is easy and works for sure) but I want that when I press j the calculator starts to run again and if not that it dont repeat itself. My problem is that when i press j nothing happens and I dont know why .. Can anyone please look where I made a logical mistake? My method: public static double Addition() { double x = 0, y = 0; double sum = x + y; String wdh = ""; System.out.println("Press j to run again"); wdh = sc.nextLine(); while (wdh == "j") { System.out.println("Enter first number"); x = sc.nextInt(); System.out.println("Enter second number"); y = sc.nextInt(); System.out.println(x + " + " + y + " = " + sum); } return sum; }

28th Oct 2017, 11:11 AM
Elsayed Salama
Elsayed Salama - avatar
5 Réponses
+ 4
If you're writing this on Code Playground then the answer is it's impossible, the Code Playground uses a one way ticket method for executing the code, it asks for inputs before sending the code and the input to the server to process, repetitively asking input like your code is doing is just unsupported in Code Playground. Your best bet would be to use an IDE in your computer/laptop, as with IDE you won't be facing such limitations. Hth, cmiiw
28th Oct 2017, 11:12 AM
Ipang
+ 3
Okay, then you can fix your code, Replace the following line: while (wdh == "j") { With something like the following: while (wdh.equals("j")) { I thought it all works, except for the loop, cause you said "(it is easy and works for sure)", and you didn't mention you used an IDE, so my first prediction went that way. String comparison in Java must use equals method, that's why it didn't work in the beginning. Hth, cmiiw
28th Oct 2017, 11:24 AM
Ipang
+ 3
You have two options, with while loop or do...while loop, here's a simple design: [With while loop] // Ask for wdh input here System.out ... wdh=sc ... while("j".equals(wdh)) { // Calculation code here... // Ask for wdh input again here } [With do...while loop] do { // Ask for wdh input here System.out ... wdh=sc ... if(!"j".equals(wdh)) break; // premature exit option // Calculation code here... } while("j".equals(wdh)); Try it out and let me know the result, about clearing console screen, I don't know how, maybe you can try searching on Google with keyword "how to clear console in java". I'll post back here if I found any working solution for clearing console screen. Hth, cmiiw
28th Oct 2017, 12:52 PM
Ipang
0
Iam using an IDE (Eclipse)
28th Oct 2017, 11:13 AM
Elsayed Salama
Elsayed Salama - avatar
0
Thank you but I want that it asks me after every loop like now it asked me once and I can execute it the whole time but I want that it asks me if I want to execute it after every loop And can you please tell me how I can clear the console after every loop? Thank you very much (I hope you understand what I mean)
28th Oct 2017, 11:27 AM
Elsayed Salama
Elsayed Salama - avatar