Java input string and math

Java User Input (Scanner)

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

Example

import java.util.Scanner; // Import the Scanner class class Main < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input >> 

If you don’t know what a package is, read our Java Packages Tutorial.

Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:

Example

import java.util.Scanner; class Main < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); >> 

Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like «InputMismatchException»).

You can read more about exceptions and how to handle errors in the Exceptions chapter.

Источник

Java String Calculator

Я пытаюсь сделать простой калькулятор в Java, который принимает ввод в виде строки и выполняет простые операции «+» и «-«.

Однозначные входы работают, но моя проблема в том, когда я пытаюсь реализовать это для двузначных

входная строка: 5+20+5+11
список 1 = [5, 20, 2, 0, 5, 11, 1]список 2 = [+, +, +]Ответ:27

Мне нужно найти способ, где после сохранения [5] в list1, как я могу добавить [5,20] вместо [5,20,2,0], что делает текущий код.

public int calC(String input) < int len = input.length(); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); for (int i = 0; i < len; i++) < if ((input.charAt(i) != '+') && (input.charAt(i) != '-')) < // check if the number is double-digit if ((i + 1 // add single digit number list1.add(input.charAt(i) - '0'); > > else < // adding the symbols list2.add(input.charAt(i)); >> int result = 0; result = result + (int) list1.get(0); for (int t = 0; t < list2.size(); t++) < char oper = (char) list2.get(t); if (oper == '+') < result = result + (int) list1.get(t + 1); >else if (oper == '-') < result = result - (int) list1.get(t + 1); >> return result; > 

Редактировать: рабочая версия
@Ker p pag спасибо за обновленные методы
входная строка: 5+20+5+11
[5, 20, 5, 11][+, +, +]Ответ:41
Мне нужно попробовать реализовать это со стеком, как предложено, но текущая версия работает

static boolean isDigit(char check) < if (Character.isDigit(check)) < return true; >return false; > public static int calC(String input) < int len = input.length(); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); for (int i = 0; i < len; i++) < if ((i + 1 else if (isDigit(input.charAt(i))) < list1.add(input.charAt(i)- '0'); >else < list2.add(input.charAt(i)); >> > int result = 0; result = result + (int) list1.get(0); for (int t = 0; t < list2.size(); t++) < char oper = (char) list2.get(t); if (oper == '+') < result = result + (int) list1.get(t + 1); >else if (oper == '-') < result = result - (int) list1.get(t + 1); >> return result; > 

9 ответов

 String a = "5+20-15+8"; System.out.println(a); String operators[]=a.split("2+"); String operands[]=a.split("[+-]"); int agregate = Integer.parseInt(operands[0]); for(int i=1;i System.out.println(agregate); 

Если вы хотите результат 41 Для входной строки «5+20+5+11» почему бы не использовать ScriptEngineManager с JavaScript двигатель,

public double calC(String input)

Но обратите внимание, что тип возвращаемого значения double Вот.

Читайте также:  Команда hello world javascript

Если вы хотите только int как тип возврата в этом случае, попробуйте с этим

return new BigDecimal(engine.eval(input).toString()).intValue(); 

Еще один способ думать об этом:

public class InlineParsing < public static void main(String []args)< String input = "5-2+20+5+11-10"; input = input.replace(" ",""); String parsedInteger = ""; String operator = ""; int aggregate = 0; for (int i = 0; i < input.length(); i++)< char c = input.charAt(i); if (Character.isDigit(c)) < parsedInteger += c; >if (!Character.isDigit(c) || i == input.length()-1) < int parsed = Integer.parseInt(parsedInteger); if (operator == "") < aggregate = parsed; >else < if (operator.equals("+")) < aggregate += parsed; >else if (operator.equals("-")) < aggregate -= parsed; >> parsedInteger =""; operator = ""+c; > > System.out.println("Sum of " + input+":\r\n" + aggregate); > > 

Это в основном конечный автомат, который пересекает каждый символ.

Итерация по каждому символу:

  1. если текущий символ представляет собой цифру, добавьте в текущий буфер чисел
  2. если текущий символ не цифра или мы разбираем последнюю цифру
    1. если оператор был проанализирован, используйте его, чтобы добавить вновь проанализированный номер к сумме, если ни один оператор не был проанализирован, установите сумму для текущего проанализированного номера.
    2. очистить текущий номерной буфер
    3. сохранить текущий символ как оператор

    Я мог бы посоветовать вам использовать Exp4j. Это легко понять, как видно из следующего примера кода:

    Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)") .variables("x", "y") .build() .setVariable("x", 2.3) .setVariable("y", 3.14); double result = e.evaluate(); 

    Особенно в случае использования более сложного выражения это может быть лучшим выбором.

    Я согласен, что стек является лучшим решением, но все же дает альтернативный способ сделать это.

     String input = "5+20+11+1"; StringBuilder sb = new StringBuilder(); List list1 = new ArrayList(); List list2 = new ArrayList(); char[] ch = input.toCharArray(); for(int i=0;ielse < list2.add(ch[i]); list1.add(Integer.valueOf(sb.toString())); sb.setLength(0); >> if(sb.length()!=0) list1.add(Integer.valueOf(sb.toString())); System.out.println(list1.size()); for(Integer i:list1)
    private static int myCal() < String[] digits = < "1", "2", "3", "4", "5" >; String[] ops = < "+", "+", "+", "-" >; int temp = 0; int res = 0; int count = ops.length; for (int i = 0; i < digits.length; i++) < res = Integer.parseInt(digits[i]); if (i != 0 && count != 0) < count--; switch (ops[i - 1]) < case "+": temp = Math.addExact(temp, res); break; case "-": temp = Math.subtractExact(temp, res); break; case "*": temp = Math.multiplyExact(temp, res); break; case "/": temp = Math.floorDiv(temp, res); break; >> > return temp; > 

    Вы можете проверить этот код, который я создал, используя только массив. Я также пробовал несколько арифметических задач, в том числе и вашу.

    См. Также комментарии к методу.

    public static String Calculator(String str) < // will get all numbers and store it to `numberStr` String numberStr[] = str.replaceAll("[+*/()-]+"," ").split(" "); // will get all operators and store it to `operatorStr` String operatorStr[] = str.replaceAll("[0-9()]+","").split(""); int total = Integer.parseInt(numberStr[0]); for (int i=0; iif(i+2 >= operatorStr.length) continue; // if meets the last operands already numberStr[i+1] = String.valueOf(total); > return String.valueOf(total); > 

    Для хранения ввода в список вы можете попробовать этот фрагмент

    for (int i = 0; i < input.length() - 1; i++) < // make a method // check if current character is number || check if current // character is number and the next character if (isDigit(input.charAt(i)) && isDigit(input.charAt(i + 1))) < list.add(input.charAt(i) +""+ input.charAt(i + 1)); >else if (isDigit(input.charAt(i))) < list.add(input.charAt(i)); >else < operator.add(input.charAt(i)); >> //check if it is a number public boolean isDigit(char input)

    импортировать java.util.ArrayList; импортировать java.util.Scanner;

    общественный класс Основной

    public static void main(String[] args) < ArrayListlistOfOpertionsCharFORM = new ArrayList<>(); ArrayList listOfNumbersCharFORM = new ArrayList<>(); ArrayList listOfNumbersINTEGERFORM = new ArrayList<>(); int Total = 0; Scanner sc = new Scanner(System.in); String input; System.out.print("Please enter your math equation :"); input = sc.nextLine(); System.out.println("string is : " + input); separator(); char[] convertAllToChar = input.toCharArray(); for (char inputToChar : convertAllToChar) < System.out.println("convertAllToChar " + inputToChar); >for (int i = 0; i < input.length(); i++) < if (convertAllToChar[i] == '+') < listOfOpertionsCharFORM.add(convertAllToChar[i]); >if (convertAllToChar[i] == '-') < listOfOpertionsCharFORM.add(convertAllToChar[i]); >if (convertAllToChar[i] == '*') < listOfOpertionsCharFORM.add(convertAllToChar[i]); >if (convertAllToChar[i] == '/') < listOfOpertionsCharFORM.add(convertAllToChar[i]); >if (Character.isDigit(convertAllToChar[i])) < listOfNumbersCharFORM.add(convertAllToChar[i]); >> separator(); for (Character aa : listOfOpertionsCharFORM) < System.out.println("list Of Operations Char FORM " + aa); >separator(); for (Character aa : listOfNumbersCharFORM) < System.out.println("list Of Numbers Char FORM " + aa); >separator(); for (Character aa : listOfNumbersCharFORM) < if (aa == '0') listOfNumbersINTEGERFORM.add(0); if (aa == '1') listOfNumbersINTEGERFORM.add(1); if (aa == '2') listOfNumbersINTEGERFORM.add(2); if (aa == '3') listOfNumbersINTEGERFORM.add(3); if (aa == '4') listOfNumbersINTEGERFORM.add(4); if (aa == '5') listOfNumbersINTEGERFORM.add(5); if (aa == '6') listOfNumbersINTEGERFORM.add(6); if (aa == '7') listOfNumbersINTEGERFORM.add(7); if (aa == '8') listOfNumbersINTEGERFORM.add(8); if (aa == '9') listOfNumbersINTEGERFORM.add(9); >for (Integer aaa : listOfNumbersINTEGERFORM) < System.out.println("list Of Numbers INTEGER FORM " + aaa); >separator(); separator(); separator(); System.out.print(listOfNumbersINTEGERFORM); System.out.print(listOfOpertionsCharFORM); System.out.println(); System.out.println(); if (listOfNumbersINTEGERFORM.size() == (listOfOpertionsCharFORM.size() + 1)) < for (int i = 0; i < listOfOpertionsCharFORM.size(); i++) < System.out.println("i :" + i); if (listOfOpertionsCharFORM.get(i) == '+') if (i == 0) < Total = Total + listOfNumbersINTEGERFORM.get(i) + listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >else < Total = Total + listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >if (listOfOpertionsCharFORM.get(i) == '-') if (i == 0) < Total = Total + listOfNumbersINTEGERFORM.get(i) - listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >else < Total = Total - listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >if (listOfOpertionsCharFORM.get(i) == '*') if (i == 0) < Total = Total + listOfNumbersINTEGERFORM.get(i) * listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >else < Total = Total * listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >if (listOfOpertionsCharFORM.get(i) == '/') if (i == 0) < Total = Total + listOfNumbersINTEGERFORM.get(i) / listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >else < Total = Total / listOfNumbersINTEGERFORM.get(i + 1); System.out.println("total : " + Total); separatorShort(); >> > else < System.out.println("*********###############**********"); System.out.println("** your input not correct input **"); System.out.println("*********###############**********"); >System.out.println("*** Final Answer *** : " + Total); > public static void separator() < System.out.println("___________________________________"); >public static void separatorShort()

    Источник

    Evaluating a math expression given in string format

    I am currently working on building a calculator using Java and JavaFX to practice my coding skills. I wrote the following methods to evaluate a given expression. What can I improve? Is there anything you would recommend me to change to optimize my program?

    public static String evaluate(String expression) < char[] tokens = expression.toCharArray(); Listlist = new ArrayList<>(); String s = ""; String operator = ""; String firstNum = ""; String secondNum = ""; boolean operationOnQueue = false; for (int i = 0; i < tokens.length; i++) < if (Character.isDigit(tokens[i])) < s += Character.toString(tokens[i]); >else < list.add(s); list.add(Character.toString(tokens[i])); if (operationOnQueue) < operationOnQueue = false; secondNum = s; list.set(list.lastIndexOf(firstNum), eval(firstNum, operator, secondNum)); list.remove(list.lastIndexOf(operator)); list.remove(list.lastIndexOf(secondNum)); >if (tokens[i] == '*' || tokens[i] == '/') < operationOnQueue = true; operator = Character.toString(tokens[i]); firstNum = list.get(list.lastIndexOf(operator) - 1); >s = ""; > if (i == tokens.length - 1 && s.length() > 0) < list.add(s); if (list.get(list.size() - 2).equals("*") || list.get(list.size() - 2).equals("/")) < firstNum = list.get(list.size() - 3); operator = list.get(list.size() - 2); secondNum = list.get(list.size() - 1); list.set(list.size() - 3, eval(firstNum, operator, secondNum)); list.remove(list.size() - 2); list.remove(list.size() - 1); >> > while (list.size() > 1) < firstNum = list.get(0); operator = list.get(1); secondNum = list.get(2); list.set(0, eval(firstNum, operator, secondNum)); list.remove(2); list.remove(1); >return list.get(0); > 
     public static String eval(String a, String operator, String b) < double r = 0; switch (operator) < case "/": r += Double.parseDouble(a) / Double.parseDouble(b); break; case "*": r += Double.parseDouble(a) * Double.parseDouble(b); break; case "-": r += Double.parseDouble(a) - Double.parseDouble(b); break; case "+": r += Double.parseDouble(a) + Double.parseDouble(b); break; >return Double.toString(r); > 

    These are the results of my tests. The first line is the string inputted, along with the answer to the expression. The second line is the output of the program.

    8+4/2+10*3+5*10 = 90 90.0 60*60+8+384/7/4-44*26 = 2477.71 2477.714285714286 64/16*18-51*7+5 = -280 -280.0 64/16*18-5100*7+5 = -35623 -35623.0 7325+92+44/4+57-84 = 7401 7401.0 14+54/9+1 = 21 21.0 7*4/7+9+12*3 = 49 49.0 

    Источник

    Evaluate a Mathematical Expression in Java

    Evaluate a Mathematical Expression in Java

    1. Evaluate a Mathematical Expression in Java
    2. Solve a String Mathematical Expression Using ScriptEngine in Java

    Evaluating a mathematical expression using a stack is one of the most common and useful options.

    Stack has two standard methods, pop() and push() , used to put and get operands or operators from the stack. The pop() method removes the top element of the expression, whereas the push() method puts an element on the top of the stack.

    Evaluate a Mathematical Expression in Java

    Here is an example in Java to evaluate a mathematical expression. This code follows the proper DMAS rules with the following precedence: Division, Multiplication, Addition, and Subtraction.

    You can give it any mathematical expression as input but ensure that the expression consists of the following four operations (Addition, Multiplication, Division, and Subtraction) only.

    package evaluateexpression;  import java.util.Scanner; import java.util.Stack;  public class EvaluateExpression    public static void main(String[] args)   Scanner scan = new Scanner(System.in);   // Creating stacks for operators and operands  StackInteger> operator = new Stack();  StackDouble> value = new Stack();   // Let's create some temparory stacks for operands and operators  StackInteger> tmpOp = new Stack ();  StackDouble> tmpVal = new Stack ();   // Enter an arthematic expression  System.out.println("Enter expression");  String input = scan.next();  System.out.println("The type of the expression is "+((Object)input).getClass().getSimpleName());  input = "0" + input;  input = input.replaceAll("-","+-");   // In the respective stacks store the operators and operands  String temp = "";  for (int i = 0;i  input.length();i++)  char ch = input.charAt(i);  if (ch == '-')  temp = "-" + temp;  else if (ch != '+' && ch != '*' && ch != '/')  temp = temp + ch;  else  value.push(Double.parseDouble(temp));  operator.push((int)ch);  temp = "";  >  >  value.push(Double.parseDouble(temp));   // Create a character array for the operator precedence   char operators[] = '/','*','+'>;   /* Evaluation of expression */  for (int i = 0; i  3; i++)  boolean it = false;  while (!operator.isEmpty())  int optr = operator.pop();  double v1 = value.pop();  double v2 = value.pop();   if (optr == operators[i])  // if operator matches evaluate and store it in the temporary stack  if (i == 0)  tmpVal.push(v2 / v1);  it = true;  break;  >  else if (i == 1)  tmpVal.push(v2 * v1);  it = true;  break;  >  else if (i == 2)  tmpVal.push(v2 + v1);  it = true;  break;  >  >  else  tmpVal.push(v1);  value.push(v2);  tmpOp.push(optr);  >  >  // pop all the elements from temporary stacks to main stacks  while (!tmpVal.isEmpty())  value.push(tmpVal.pop());  while (!tmpOp.isEmpty())  operator.push(tmpOp.pop());  // Iterate again for the same operator  if (it)  i--;  >  System.out.println("\nResult = "+value.pop());  > > 
    Enter expression 2+7*5-3/2 The type of the expression is String  Result = 35.5 

    As you can see in the output of the above code, the expression 2+7*5-3/2 was given as input. And the program has calculated the result as 35.5 .

    It first divided 3/2 = 1.5 because, in DMAS rules, the division has the highest precedence. Then the multiplication part is calculated as 7*5 = 35 .

    Next, we have an addition of 2+35 = 37 , and the last part of the expression is a subtraction that is 37 -1.5 = 35.5 .

    Solve a String Mathematical Expression Using ScriptEngine in Java

    In our example below, we illustrated how we could solve a mathematical expression in string format using the ScriptEngine . Take a look at our below code:

    import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException;  public class EvaluateExpLib   public static void main(String[] args) throws ScriptException   ScriptEngineManager MyMgr = new ScriptEngineManager(); // Declaring a "ScriptEngineManager"  ScriptEngine MathEng = MyMgr.getEngineByName("JavaScript"); // Declaring a "ScriptEngine"  String Exp = "300+2-3";  System.out.println("The result is: "+MathEng.eval(Exp));  > > 

    We have commanded the purpose of each line. Now, after running the example code, you will see the below output:

    Remember, you may need JDK1.6 to run the above example.

    Please note that the example codes shared in this article are in Java, and you must install Java on your environment if your system doesn’t contain Java.

    Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

    Related Article — Java Math

    Источник

Оцените статью