有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过文件输入计算最小/最大值

在我的java程序中,我需要文件输入部分的最高值和最低值“answer”,并将它们显示回控制台。我知道如何运用数学。敏/数学。max命令,但无法看到如何将它们纳入我的代码中

import java.util.ArrayList;
import java.util.Scanner; 
import java.io.*;

public class Assignment {
private static Scanner input;
public static ArrayList<String> validList = new ArrayList<String>(); 


public static boolean isInt(String userinput) { 
        try {
            Integer.parseInt(userinput); // Try to parse. Makes sure    that the values entered are actual numbers
            return true; // Boolean value to show if the equation entered is valid or not
        } 
        catch (NumberFormatException e) { 
            System.out.println("Please enter a  valid expression!");
            return false; 
        }
    }
        public static boolean isValidLine(String line) {
            line = line.trim();
        if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
                return false; 
            } 
        else 
            {
            String[] calcarray = new String[3];
            calcarray = line.split(" ");
            String operators = new String("[+\\-\\*\\/]"); // Validator using regular expressions to check the operator used

        if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression 
            return true; 
    }
        else 
    {
            return false;
    }
    }
}

static void display(String msg)
        {
            System.out.println(msg);
        }
static void processInput() throws IOException
{
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true){
        display("Please enter an equation");
        keyboardInput = kbScan.nextLine(); 
if (isValidLine(keyboardInput)) {
    String[] equation = new String[3];  // We know that this is only going to contain 3 to be valid
    equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]); 
int num2 = Integer.parseInt(equation[1]);
switch(equation[2]) { // This case switch checks the third position of the string to decide which operator is being used. It then works out the answer and breaks to the next instruction

case("+"):
    answer = num1 + num2;
break;
case("-"):
    answer = num1 - num2; 
break; 
case("/"):
    answer = num1 / num2;
break;
case("*"):
    answer = num1 * num2;
break;
}
    display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
    display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
}
else
{ 
    display("The equation you entered is invalid");
}
}
    }

static void fileInput() throws IOException
{
    input = new Scanner(System.in);
    try
    {
    String currentLine = new String();
    int answer = 0;
    //Open the file
    display("Enter File Name: "); 
    FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
    String strLine; // create string vars
    //loop to read the file line by line
    while ((strLine = br.readLine()) != null)   { // Whilst the buffered readers read line method is not null, read and validate it.
        currentLine = strLine; 
        if(strLine.trim().isEmpty())
        { 
            display("You have entered a blank line, the program will now exit");
            System.exit(0); 
            }
    if(isValidLine(currentLine)) 
    { 
        String[] filearray = new String[3];
        filearray = currentLine.split(" ");             
    int val1 = Integer.parseInt(filearray[0]);
    int val2 = Integer.parseInt(filearray[1]);
        display("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
    switch(filearray[2]) { 
    case("+"):
            answer = val1 + val2;
        break;
    case("-"):
            answer = val1 - val2; 
        break; 
    case("/"):
            answer = val1 / val2;
        break;
    case("*"):
            answer = val1 * val2;
        break;
        }
    display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
    }
    }
    }
catch (FileNotFoundException e) 
{
    display("Please Enter a valid file name");
}
}

public static void main(String[] args) throws IOException {
while(true)
{
    display("Enter F for file calculator or K for keyboard input");
Scanner optionScan = new Scanner (System.in);
String optionInput = optionScan.nextLine();
char letterInput = optionInput.charAt(0);

switch (Character.toUpperCase(letterInput))
{
case 'K':
    processInput();
    break;
case 'F':
    fileInput();
    break;
case 'Q':
    System.exit(0);
}
}

}   
}

共 (1) 个答案

  1. # 1 楼答案

    我会使用2private static字段来跟踪你的最小和最大答案。首先,我将用其他字段创建两个新字段。我给了他们最大整数值和最小整数值,这样以后比较就容易了

    private static Scanner input;
    public static ArrayList<String> validList = new ArrayList<String>(); 
    private static int minAnswer = Integer.MAX_VALUE;
    private static int maxAnswer = Integer.MIN_VALUE;
    

    然后在fileInput方法中,在计算之后,这里是可以利用Math.maxMath.min的地方。比如:

    display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
    minAnswer = Math.min(answer, minAnswer);
    maxAnswer = Math.max(answer, maxAnswer);
    
    <>用户输入到ExCAPE的空白行后,将在这些字段中获得最大值和最小值答案。希望这有帮助

    编辑:我创建了字段,因为我认为您需要访问主方法中的最小/最大值。如果您只需要在fileInput方法中访问这些值(完成所有计算后打印这些值,然后忘记它们),那么我只需要在fileInput方法中创建2int局部变量