import java.util.Scanner;
public class WorkArea {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String errorMessage = "Invalid input entered. Terminating...";
do {
System.out.println("Operations: add subtract multiply");
System.out.println("Enter an operation:");
String operation=input.next();
switch(operation.toLowerCase())
{
case "add":
System.out.println("Enter two integers:");
if (input.hasNextInt())
{
int int1=input.nextInt();
if (input.hasNextInt())
{
int int2=input.nextInt();
System.out.println("Answer:"+(int1+int2));
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
case "subtract":
System.out.println("Enter two integers:");
if (input.hasNextInt())
{
int int1=input.nextInt();
if (input.hasNextInt())
{
int int2=input.nextInt();
System.out.println("Answer:"+(int1-int2));
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
case "multiply":
System.out.println("Enter two integers:");
if (input.hasNextDouble())
{
double double1=input.nextDouble();
if (input.hasNextDouble())
{
double double2=input.nextDouble();
System.out.printf("Answer:%.2f\n",double1*double2);
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
default:
System.out.println(errorMessage);
break;
}
}while(!operation.equals("add")||!operation.equals("subtract")||!operation.equals("multiply"));
}
}
Я попробовал цикл do- while для выполнения операций, которые я неоднократно перечислял во фрагменте, сравнивая строку со случаем переключателя. Я ожидаю, что программа должна завершить работу, если операция отсутствует в списке.
while(!operation.equals("add")||!operation.equals("subtract")||!operation.equals("multiply"));
while(!operation= = "add"||"subtract"||"multiply");
while(!operation.equals("multiply"));
когда я сравниваю строку с помощью цикла do- while, результат говорит: «операция не может быть разрешена». Как я могу выполнить несколько операций, используя цикл do- while в одном окне консоли?
operation
должен быть определен вне вашего цикла, иначе он выйдет за рамки. Кроме того, while(!operation.equals("add")||!operation.equals("subtract")||!operation.equals("multiply"))
всегда true
, вы хотите использовать &&
здесь
Вопрос закрыт как дубликат, как и должно быть. Но в закрытом уведомлении указан неверный дубликат. Проблема здесь в области переменных. String
сравнение в коде здесь не проблема.
Переменные, определенные внутри цикла, будут иметь область действия блока, т. е. их можно использовать только внутри тела цикла. В вашем коде переменную операции можно использовать только внутри тела цикла. Изменение вашей программы -
import java.util.Scanner;
public class WorkArea {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String errorMessage = "Invalid input entered. Terminating...";
String operation = null;
do {
System.out.println("Operations: add subtract multiply");
System.out.println("Enter an operation:");
operation=input.next();
switch(operation.toLowerCase())
{
case "add":
System.out.println("Enter two integers:");
if (input.hasNextInt())
{
int int1=input.nextInt();
if (input.hasNextInt())
{
int int2=input.nextInt();
System.out.println("Answer:"+(int1+int2));
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
case "subtract":
System.out.println("Enter two integers:");
if (input.hasNextInt())
{
int int1=input.nextInt();
if (input.hasNextInt())
{
int int2=input.nextInt();
System.out.println("Answer:"+(int1-int2));
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
case "multiply":
System.out.println("Enter two integers:");
if (input.hasNextDouble())
{
double double1=input.nextDouble();
if (input.hasNextDouble())
{
double double2=input.nextDouble();
System.out.printf("Answer:%.2f\n",double1*double2);
}else{
System.out.println(errorMessage);
}
}else{
System.out.println(errorMessage);
}
break;
default:
System.out.println(errorMessage);
break;
}
}while(!operation.equals("add")||!operation.equals("subtract")||!operation.equals("multiply"));
Из приведенной выше программы я получаю «обнаружение операции с учетом регистра во время выполнения, если я изменю строку на System.out.println(»Введите операцию:»); Operation=input.next().toLowerCase(); Почему я получаю ту же ошибку времени выполнения? Спасибо.
@PriyadhanamPriyadhanam Я не понимаю контекст для «обнаружения операции с учетом регистра». Не могли бы вы это прояснить? Но следует отметить, что помимо проблемы с областью действия переменной, существует логическая ошибка: см. комментарий от QBrute в комментариях под вопросом.
Замените
String operation=input.next();
наoperation=input.next();
и добавьтеString operation;
передdo {
. Переменнаяoperation
находится вне области видимости в}while (!operation.equals ...
. См. stackoverflow.com/questions/8068814/scope-of-do- while-loop и другие.