JAVA程序员减少,Java可以选择添加或减少

I have two question, first is why cant I add an operator , I can add first and 2nd integer but not an operator.

2nd question is I need to create a never ending loop is there an easier way than the while loop? basically the idea is that if for example they choose * if will say wrong operator please try again

import java.util.Scanner;

public class Uppgift5 {

public static void main (String[] args){

int tal1, tal2;

int sum = 0;

int sub=0;

String operator;

Scanner input = new Scanner (System.in);

System.out.println("write in first digit");

tal1 = input.nextInt();

System.out.println("Write in 2nd digit ");

tal2 = input.nextInt();

System.out.println("Enter + to add and - subtract ");

operator = input.nextLine();

while (operator.equals('-') || operator.equals('+')|| operator.equals('*') || operator.equals(('/')) ){

if (operator.equals("+")){

sum = tal1+tal2;

System.out.println("the sum is " + sum);

}

else if (operator.equals("-")){

sub = tal1-tal2;

System.out.println("the subtracted value is " + sub);

}

System.out.println("You have put in the wrong operator, your options are + or -");

}

}

}

解决方案

The nextInt method does not consume the whitespace characters (newline) that you input when you press the carriage return on your keyboard. When you then call

operator = input.nextLine();

All that reads is that new line character. You need to add an extra

nextLine();

call after the nextInt() so that it can consume the danglign \n (or \r\n depending on your system) character.

Scanner input = new Scanner (System.in);

System.out.println("write in first digit");

tal1 = input.nextInt();

System.out.println("Write in 2nd digit ");

tal2 = input.nextInt();

input.nextLine();

System.out.println("Enter + to add and - subtract ");

operator = input.nextLine();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值