Java可以选择添加或减少 [英] Java being able to choose wether to add or subract

查看:128
本文介绍了Java可以选择添加或减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题,首先是为什么我不能添加运算符,我可以添加第一个和第二个整数但不能添加运算符。

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

第二个问题是我需要创建一个永无止境的循环是否比while循环更简单?基本上这个想法是,如果他们选择*如果会说错误的运算符请再试一次

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 -");
}

}

}

推荐答案

nextInt 方法不会消耗您按下时输入的空格字符(换行符)键盘上的回车。然后你打电话

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();

nextInt()之后调用,以便它可以消耗danglign \ n (或 \\\\ n ,具体取决于您的系统)字符。

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();

这篇关于Java可以选择添加或减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆