我一直在尝试对以下程序进行编码,以便当用户输入"停止"或者" s",程序将终止,但直到他输入该单词,它将继续要求用户输入数字以平方根。这是我的代码到目前为止,在功能方面它很好,但我似乎无法做到这一点。谢谢大家。
import java.util.Scanner;
public class Question5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double input, var = 0.0, var2 = 0.0; //initialising variables
String x;
System.out.println("Input the number to calculate square root on");
input = sc.nextDouble(); //inputting by the user
while(!x.equals("stop")) {
x = sc.next();
if (input < 0) { //negative numbers cannot be entered
System.out.println("Negative numbers are not computable in this case");
System.exit(1);
}
double RepeatedInp = input;
while (true) {
//calculation of square root of number inputted
var = ((RepeatedInp + input / RepeatedInp) / 2.0);
RepeatedInp = var;
if (var2 == var) {
break;
}
var2 = var;
}
System.out.println(var); //printing
}
}
}
答案 0 :(得分:0)
您可以使用Scanner或BufferReader。这里有很多细节:Scanner vs. BufferedReader
使用扫描仪:它等待行尾(您必须按返回)。
// INPUT LOOP
System.out.println(“输入你的公式(停止停止):”);
Scanner s = new Scanner(System.in);
String line;
while ((line=s.nextLine())!=null)
{
System.out.println("LINE:'"+line+"'");
// IF STOP:
if (line.contentEquals("stop"))
break;
if (line.contentEquals("s"))
break;
// do what you want
System.out.println("TYPE YOUR FORMULA (s ou stop to STOP):");
}
// while ((line=s.nextLine())!=null)
// safe
s.close();
要直接获取字符,请参阅:How to read a single char from the console in Java (as the user types it)?