我最近開始編程,這個程序是一個類。我只需要一些關於如何解決這個問題的建議。我掌握了所有的信息,但當我給它終端價值時,我的循環從不想退出。它運行良好,但有問題離開循環沒有完全退出。任何幫助,將不勝感激。雖然循環不終止
import java.util.Scanner;
public class Calc
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int first = 0, second = 0, sum = 0, numLines = 0, max = -2147483646;
int min = 2147483647;
char inop = 'a';
final int TERMINAL = -999;
System.out.println("==================");
System.out.println("Simple calculator");
System.out.println("==================");
while(first != TERMINAL)
{
numLines++;
first = checkFirst(scan);
inop = checkOp(scan);
second = checkSecond(scan);
sum = calculateSum(first, inop, second);
debugSwitch();
if(sum >= max)
{
max = sum;
}
if(min >= sum)
{
min = sum;
}
System.out.println(sum);
debugSwitch(numLines, max, min);
first = checkFirst(scan);
}
System.out.println("Number of lines read: " + numLines);
System.out.println("Maximum calculated value: " + max);
System.out.println("Minimum calculated value: " + min);
}
public static int checkFirst(Scanner scan)
{
int first = 0;
if(scan.hasNextInt())
{
first = scan.nextInt();
}
else
{
System.out.println("Not an integer");
System.exit(0);
}
return first;
}
public static char checkOp(Scanner scan)
{
final char OPERATOR1 = '+';
final char OPERATOR2 = '-';
final char OPERATOR3 = '*';
final char OPERATOR4 = '/';
char input = 'a';
String str = "";
if(scan.hasNext())
{
str = scan.next();
}
else
{
System.out.println("No input");
System.exit(0);
}
input = str.charAt(0);
if(input == OPERATOR1)
{}
else if(input == OPERATOR2)
{}
else if(input == OPERATOR3)
{}
else if(input == OPERATOR4)
{}
else
{
System.out.println("Not a valid operator");
System.exit(0);
}
return input;
}
public static int checkSecond(Scanner scan)
{
int second = 0;
if(scan.hasNextInt())
{
second = scan.nextInt();
}
else
{
System.out.println("Not an integer");
System.exit(0);
}
return second;
}
public static int calculateSum(int first, char inop, int second)
{
int sum = 0;
final char OPERATOR1 = '+';
final char OPERATOR2 = '-';
final char OPERATOR3 = '*';
final char OPERATOR4 = '/';
if(inop == OPERATOR1)
{
sum = first + second;
}
else if(inop == OPERATOR2)
{
sum = first - second;
}
else if(inop == OPERATOR3)
{
sum = first * second;
}
else if(inop == OPERATOR4)
{
sum = first/second;
}
return sum;
}
public static void debugSwitch(int numLines, int max, int min)
{
final Boolean DEBUG_SW = true;
if(DEBUG_SW)
{
System.out.println("Debug Information:");
System.out.println("Number of lines read = " + numLines);
System.out.println("Current max: " + max);
System.out.println("Current min: " + min);
}
}
}
在我看來,「checkFirst」和「checkSecond」方法是否完全相同? –
如果你在'first'中傳遞一個值'-999',那麼這個循環將會終止。你能再詳細一點嗎?你如何運行你的代碼?你的預期產出是多少? –
@JanDvorak。大聲笑。他們的確是一樣的。別擔心,你沒有'弱視力';) –