Java - 解析简单计算器程序的字符串的问题

weixin_38059951 2019-09-12 03:14:17

我有代码需要输入,然后计算出你想要用它做什么 例如。你会输入“x(+, - ,.. etc)y”,它会为你计算它。 即时通讯目前使用扫描仪和分裂它使得 double x = input.nextDouble(); String z = input.next(); double y = input.nextDouble(); 现在我遇到了一个问题。说我想做一个阶乘,我会输入“x!”但代码仍然需要最后一次input.nextDouble(); 我该怎么去(使用我在做的事情,如果可能的话)检查是否所有3都有输入,然后在使用if语句的方法之间进行选择,或者只有2个输入。 相对码 System.out.print("> "); double x = input.nextInt(); String z = input.next(); double y = input.nextInt(); if (x == 0) { running = false; } else if (z.equalsIgnoreCase("+")) { System.out.println(addition(x, y)); }








...全文
86 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38068392 2019-09-12
  • 打赏
  • 举报
回复

相反获得三个不同的输入,只是输入串的一行的,因此分析该字符串,并输入它们转换成所需类型。通过这种方式,您可以从字符串中确定一个因子(1个变量)或其他任何操作。 使用扫描仪。 boolean binary = true; Scanner input = new Scanner(System.in); double x = input.nextInt(); String z = input.next(); //check if z is a unary operator ie. if(z=='!') binary = true; if(binary) double y = input.nextInt();
weixin_38073649 2019-09-12
  • 打赏
  • 举报
回复

如果您有两个输入,那么您的代码将抛出NoSuchElementException。为了避免这种情况,您应该使用input.hasNext()。 double x = input.nextInt(); String z = input.next(); if (input.hasNext()) { // input has y y = input.nextInt(); // perform operation on two elements } else { // no y // perform operation on one element }
weixin_38075910 2019-09-12
  • 打赏
  • 举报
回复

添加一个额外的if语句,并且仅当z ='+'时才要求'y'。 System.out.print("> "); double x = input.nextInt(); String z = input.next(); if (x == 0) { running = false; } else if(z.equalsIgnoreCase("!")){ factorial(x); } else if (z.equalsIgnoreCase("+")) { double y = input.nextInt(); System.out.println(addition(x, y)); }
weixin_38076856 2019-09-12
  • 打赏
  • 举报
回复

试试这个代码 double y = 0.0; if(!z.contains("!")){ y = sc.nextDouble(); }
weixin_38090265 2019-09-12
  • 打赏
  • 举报
回复

你必须得到输入的字符串,所以你必须使用String.indexof()和划分主串两个字符串必须parse像第一部分这个: int a=Integer.parse(someString); 和你的钢琴的第二部分克会告诉你你必须做什么。

436

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧