java - Stopping a repeating Println in a while loop, BlueJ -
below code have far, calculator computer science class. problem having on second run of program system.out.print("would perform calculation? (y/n) "); runs twice instead of once. have turned in project, know why , how, in future programs, can fix it. i'll post rest of code below.
i appreciate of help, credit "a" got on of you. thanks!
/** * calculator multiple functions. * @author () * @version (version 2.1) */ import java.io.*; import java.util.scanner; public class calc { public static void main(string args[]) { scanner reader = new scanner(system.in); string cont = "", funct = ""; double fnum = 0, snum = 0, answer = 0; while(true) { system.out.print("would perform calculation? (y/n) "); cont = reader.nextline(); if (cont.equalsignorecase("y")) { system.out.println("what function do?"); system.out.println("+?"); system.out.println("-?"); system.out.println("*?"); system.out.println("/?"); funct = reader.nextline(); if (funct.equals("+")) { system.out.println("simple addition calculator"); system.out.println("enter first num: "); fnum = reader.nextdouble(); system.out.println("enter second num: "); snum = reader.nextdouble(); answer = fnum + snum; system.out.println("answer: " + answer); system.out.println(" "); } if (funct.equals("-")) { system.out.println("simple subtraction calculator"); system.out.println("enter first num: "); fnum = reader.nextdouble(); system.out.println("enter second num: "); snum = reader.nextdouble(); answer = fnum - snum; system.out.println("answer: " + answer); system.out.println(" "); } if (funct.equals("*")) { system.out.println("simple multiplication calculator"); system.out.println("enter first num: "); fnum = reader.nextdouble(); system.out.println("enter second num: "); snum = reader.nextdouble(); answer = fnum * snum; system.out.println("answer: " + answer); system.out.println(" "); } if (funct.equals("/")) { system.out.println("simple division calculator"); system.out.println("enter first num: "); fnum = reader.nextdouble(); system.out.println("enter second num: "); snum = reader.nextdouble(); answer = fnum / snum; system.out.println("answer: " + answer); system.out.println(" "); } } else if (cont.equalsignorecase("n")) { break; } } } }
in of function conditions inside loop, using reader.nextdouble(). read number (e.g "8") input not new line (the enter) entered user after number. following code minus(-) function not print "would perform calculation? (y/n) " twice new line read. here reader.nextline() used instead of reader.nextdouble(). reader.nextline() read whole line not number.
if (funct.equals("-")) { system.out.println("simple subtraction calculator"); system.out.println("enter first num: "); fnum = double.parsedouble( reader.nextline()); system.out.println("enter second num: "); snum = double.parsedouble( reader.nextline()); answer = fnum - snum; system.out.println("answer: " + answer); system.out.println(" "); }
Comments
Post a Comment