Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Tarantula83 avatar Tarantula83 3 Точки

Задача Operations Between Numbers ???

Здравейте колеги.

Трябва малко помощ тук какъвто и вход да дам винаги печата 0,изобщо не влиза в проверките като прегледах кода с дебъгера къде бъркам?

Ето го и кода:

import java.util.Scanner;

public class OperationsBetweenNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        double n1 = Double.parseDouble(scanner.nextLine());
        double n2 = Double.parseDouble(scanner.nextLine());
        String operator = scanner.nextLine();

        double result = 0 ;


        if (operator == "+") {
             result = n1 + n2;
            if (result % 2 == 0) {

                System.out.printf("%d +  %d  =  %d - even", n1,n2, result);
            } else {
                System.out.printf("%d +  %d = %d - odd", n1,n2, result);
            }

        } else if (operator == "-") {
             result = n1 - n2;
            if (result % 2 == 0) {
                System.out.printf("%d - %d = %d - even", n1, n2, result);
            } else {
                System.out.printf("%d - %d = %d - odd", n1, n2, result);
            }

        } else if (operator == "*") {
             result = n1 * n2;
            if (result % 2 == 0) {
                System.out.printf("%d * %d = %d - even", n1, n2, result);
            } else {
                System.out.printf("%d * %d = %d - odd", n1, n2, result);
            }
        } else if (operator == "/") {
             result = n1 / n2;
            if (n2 != 0) {
                System.out.printf("%d / %d = %.2f", n1, n2, result);
            } else {
                System.out.printf("Cannot divine %d by zero", n1);
            }

        } else if (operator == "%") {
             result = n1 % n2;
            if (n2 != 0) {
                System.out.printf("%d % %d = %.2f", n1, n2, result);
            } else {
                System.out.printf("Cannot divine %d by zero", n1);
            }
        }
        System.out.println(result);
    }
 }

 

Благодаря предварително!

Тагове:
0
Programming Basics
Vasetoo0 avatar Vasetoo0 5 Точки
package nestedConditionalStatements;

import java.util.Scanner;

public class OperationsBetweenNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N1 = Integer.parseInt(scanner.nextLine());
        int N2 = Integer.parseInt(scanner.nextLine());
        String operator = scanner.nextLine();

        int result = 0;


        if ("+".equals(operator)) {
            result = N1 + N2;
            if (result % 2 == 0) {
                System.out.printf("%d + %d = %d - even", N1, N2, result);
            } else {
                System.out.printf("%d + %d = %d - odd", N1, N2, result);
            }
        } else if ("-".equals(operator)) {
            result = N1 + N2;
            if (result % 2 == 0) {
                System.out.printf("%d - %d = %d - even", N1, N2, result);
            } else {
                System.out.printf("%d - %d = %d - odd", N1, N2, result);
            }
        } else if ("*".equals(operator)) {
            result = N1 * N2;
            if (result % 2 == 0) {
                System.out.printf("%d * %d = %d - even", N1, N2, result);
            } else {
                System.out.printf("%d * %d = %d - odd", N1, N2, result);
            }
        } else if ("/".equals(operator)) {
            result = N1 / N2 ;
            if (N2 != 0) {
                System.out.printf("%d / %d = %.2f", N1, N2, result);
            } else {
                System.out.printf("Cannot divide %d by zero", N1);
            }
        } else if ("%".equals(operator)) {
            result = N1 % N2;
            if (N2 != 0) {
                System.out.printf("%d %% %d = %d", N1, N2, result);
            } else {
                System.out.printf("Cannot divide %d by zero", N1);
            }
        }

        System.out.println(result);


    }
}

 

 

 

 

На мен изобщо не ми тръгва? Дава ми Exception in thread "main" java.lang.ArithmeticException: / by zero. Някой знае ли как да го подкарам?

0
Tarantula83 avatar Tarantula83 3 Точки

Новият код ми дава 50/100 точки.

Гърми на вход 123, 12, / моят резултат е 123 / 12 = 010:

а трябва да бъде 123 / 12 = 10.25 как да го оправя?

Ето го и кода:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;

public class OperationsBetweenNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n1 = Integer.parseInt(scanner.nextLine());
        int n2 = Integer.parseInt(scanner.nextLine());
        String operator = scanner.nextLine();

        BigDecimal result = new BigDecimal("0.00");
        String output = "";
        DecimalFormat intFormatter = new DecimalFormat("0");

        if (n2 == 0 && (operator.equals("/") || operator.equals("%"))) {
            output = String.format("Cannot divide %d by zero", n1);

        } else if (operator.equals("/")) {
            result = new BigDecimal(n1).divide(new BigDecimal(n2), 2, RoundingMode.HALF_UP);
            DecimalFormat decimalFormatter = new DecimalFormat("0:00");
            output = String.format("%d %s %d = %s", n1, operator, n2, decimalFormatter.format(result));

        } else if (operator.equals("%")) {
            result = new BigDecimal(n1).remainder(new BigDecimal(n2));
            output = String.format("%d %s %d = %s", n1, operator, n2, intFormatter.format(result));

        } else {
            if (operator.equals("+")) {
                result = new BigDecimal((n1 + n2));
            } else if (operator.equals("-")) {
                result = new BigDecimal((n1 - n2));
            } else if (operator.equals("*")) {
                result = new BigDecimal((n1 * n2));

            }
            output = String.format("%d %s %d = %s - %s", n1, operator, n2, intFormatter.format(result), result.intValueExact() % 2 == 0 ? "Even" : "odd");
        }
        System.out.println(output);
    }

}
0
AleksandarGrigorov avatar AleksandarGrigorov 0 Точки

Защото, делението трябва да го кастнеш към (double). Ето мойто решение, дано съм бил полезен.

https://pastebin.com/zL7cNrD1

0
markopizzy avatar markopizzy 0 Точки

Колега това кастване към double е много добре, но поне аз не съм го видял на лекция. Има ли го някъде казано?

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.