【问题标题】:Is there a way to create a simple equation using scanner有没有办法使用扫描仪创建一个简单的方程
【发布时间】:2020-02-06 07:17:57
【问题描述】:

我是 java 的初学者,我想弄清楚为什么扫描仪中不允许使用“不带空格”的运算符的 2 个操作数。

我正在尝试做一个输出

enter an operand with an operator and another operand: 
1+1 
The answer is: 2.0 

第一行和最后一行都可以理解,但是第二行我以为会很简单,但是放1+1的时候就报错了。但是,当我执行 1 + 1 时,它可以工作(带空格)。我在扫描仪中声明了 3 个要输入的变量:

double input1 = keyboard.nextDouble();
char operator = keyboard.next().charAt(0);
double input2 = keyboard.nextDouble();

我尝试了这个,但发生了错误,但是通过使用扫描仪(上图)执行 1 + 1 可以正常工作。有没有办法去除操作数和运算符之间的空格?

【问题讨论】:

  • String [] nums = keyboard.nextLine().split("+") - 使用 Integer.valueOf(nums[0]) 等
  • 但扫描仪必须能够读取任何不特定的运算符以及为什么是数组?
  • 在这种情况下,您最好找到一个为您执行此操作的库。

标签: java java.util.scanner next removing-whitespace


【解决方案1】:

这不起作用,因为您没有输入空格。尝试分别输入就像输入 1 和 enter 然后 + 和 enter 然后 1。 希望对您有所帮助。

import java.util.*;
import java.io.*;
public class operations{
   public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the equation");
      String eq  = sc.nextLine();
      System.out.println(eq);
      String[] result = eq.split("(?<=[-+*/])|(?=[-+*/])");
      System.out.println(result[0]);
      System.out.println(result[1]);
      System.out.println(result[2]);
   }
}  

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多