0

This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc. I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/ Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;


public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be 
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();        
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something 
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
SlimE
  • 45
  • 1
  • 4
  • 2
    you are calling `nextInt` on the scanner instance, but `+` is not – guido Jul 07 '17 at 09:02
  • 1
    Please try to use real words here - "you" is not harder to type than "u". This makes posts readable for a wide audience, including people whose first language is not English. Thanks! – halfer Jul 07 '17 at 10:04

8 Answers8

2

First of all, when you are reading the operation sign you need to read it as an String since it is not an Integer. Moreover, when comparing Strings you should use the equals method. Finally, when performing the division you should cast one of the operands to float to obtain a float result (otherwise you will obtain the casted division - int -).

This said, your code should look like:

import java.util.Scanner;


public class Taschenrechner {

    public static void calculator() {
        Scanner input = new Scanner(System.in);
        // Read input numbers
        System.out.println("Give me the 2 numbers first: ");
        int x = input.nextInt();
        int y = input.nextInt();

        // Read operation
        System.out.println("Now give me the operation (+,-,*,/): ");
        String operation = input.next();

        // Perform operation
        float result = 0;
        if (operation.equals("+")) {
            result = x + y;
        } else if (operation.equals("-")) {
            result = x - y;
        } else if (operation.equals("*")) {
            result = x * y;
        } else if (operation.equals("/")) {
            // Add float casting to one of the operands to obtain a float result
            result = x / ((float) y);
        } else {
            System.err.println("ERROR: Unrecognised operation " + operation);
        }

        // Print result
        System.out.println("Result: " + result);

        // Close scanner
        input.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}

Notice that:

  • I have moved the result print to the end of the function since you are duplicating code.
  • I have added an else case for the operations that are not supported.
  • The Strings are compared using the equals method.
  • If you want you can change the if, if-else, else by a switch-case.
Cristian Ramon-Cortes
  • 1,675
  • 1
  • 17
  • 26
1
Give me the 2 numbers first: 
1
2
Now give me the operation (+,-,*,/): 
+
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Taschenrechner.Operationen(Taschenrechner.java:10)
    at Taschenrechner.main(Taschenrechner.java:30)

Means:

After inputting + there was an Exception thrown. It's InputMismatchException. It was thrown in (...) Scanner#nextInt in Taschenrechrer.java in line 30.

In the provided code, there are also three different problems. One is that you should distinguish between "x" and ''. The first one is a String, the other is a char.

The other one is the fact, that you probably expect floating division instead of integer, so you have to add 1.0 before dividing. Otherwise, the result will always be an integer.

But the most important one is the fact, that scanner is associated with the input stream. A stream is something that floats and can't fall back. This means, that you have to read the input once and then compare what it is. Calling a.next() three times will cause scanner reading 3 different inputs.

public class Taschenrechner {

    public static void calculator(){
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        String op = a.next();
        if (op.equals("+"){
            float result = x + y;
            System.out.println("result: " + result);
        }
        else if (op.equals("-")){
            float result = x - y;
            System.out.println("result: " + result);
        }
        else if (op.equals("*")){
            float result = x * y;
            System.out.println("result: " + result);
        }
        else{
            float result = 1.0 * x / y;
            System.out.println("result: " + result);
            }
        a.close();
        }

        public static void main(String []args) {
            calculator();
        }

}
xenteros
  • 14,275
  • 12
  • 47
  • 81
1

I will go through your code and suggest some refactoring.

 if (a.nextInt()=='+'){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='-'){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='*'){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
}

You read operation each time if it is not equal to what you coded. So if user wants to enter opearation -, they have to enter first time operation different from +, and then -.

Second, it is a good practice to move hardcoded constants into private static fields (or public static if they are used in other classes).

Instead of if-else, prefer to use switch (for primitives, strings, enums) - better style and performance (JVM optimizes switch).

This is how I would code this

Taschenrechner

public class Taschenrechner {

    private static final char ADD = '+';
    private static final char SUB = '-';
    private static final char MUL = '*';
    private static final char DIV = '/';


    public static void calculate() {
        Scanner reader = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = reader.nextInt();
        int y = reader.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        final char operation = reader.next(".").charAt(0); //See explanation bellow.
        float result = calculateResult(x, y, operation);
        System.out.println("result: " + result);
        reader.close();
    }

    private static float calculateResult(float x, float y, char operation) {
        switch (operation) {
            case ADD:
                return x + y;

            case DIV:
                return x / y;

            case SUB:
                return x - y;

            case MUL:
                return x * y;

            default:
                throw new UnsupportedOperationException(operation + " is not suported."); //Terminate the program with an error. Read about exception handling to understand when it can be used.
        }
    }

    public static void main(String[] args) {
        calculate();
    }
}

final char operation = reader.next(".").charAt(0); I want to read only one character. https://stackoverflow.com/a/13942707/4587961

I also renamed method calculator into calculate. I am a big fan of Clean Code practices. Methods' names are verbs, while classes names are nouns.

Yan Khonski
  • 9,178
  • 13
  • 52
  • 88
0

You are using a.nextInt() which is used for taking integer as input. Just use a.next().charAt(0) instead of that. This is working

import java.util.Scanner;

public class Taschenrechner {
    public static void calculator() {
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        if (a.next().charAt(0) == '+') {
            float result = x + y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '-') {
            float result = x - y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '*') {
            float result = x * y;
            System.out.println("result: " + result);
        } else {
            float result = x / y;
            System.out.println("result: " + result);
        }
        a.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}
Bharat
  • 996
  • 10
  • 30
0

To get the mathematical operators you have used nextInt.

a.nextInt()=='+'

This is the cause of the problem. Also, use switch to make the code more robust and readable.

Ashish Lohia
  • 259
  • 1
  • 11
0

it will work

public static void calculator() {
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();

    System.out.println("Now give me the operation (+,-,*,/): ");
    String choice = a.next();
    if (choice.equals("+")) {
        float result = x + y;
        System.out.println("result: " + result);
    }
    if (choice.equals("-")) {
        float result = x - y;
        System.out.println("result: " + result);
    }
    if (choice.equals("*")) {
        float result = x * y;
        System.out.println("result: " + result);
    }
    if (choice.equals("/")) {
        float result = x / y;
        System.out.println("result: " + result);
    }
    a.close();
}
Pavan Kumar
  • 425
  • 1
  • 5
  • 15
-1
if (a.nextInt()=='+'){
    float result = x + y;
    System.out.println("result: " + result);
}

a.nextInt() expect an "int", but you're passing to it a char. You have two possibilities.

  1. Create another scanner which will take "char"
  2. Use the method "next()". Like this : a.next(); In the second case, use .equals("your operation"), cause you can't compare strings with "==".
LeXcution
  • 1
  • 3
  • 1
    Note that `a.next()` returns a `String` rather than a `char`, and that you can't compare `String`s with `==` (nor compare `String`s with `char`s) – Aaron Jul 07 '17 at 09:10
-2

In your code have 2 problem

  1. when input mathematics must string not Integer
  2. When compare mathematics, must using character " not using '. Because character " have meaning string and ' just meaning character

So, please try this code below

public static void calculator(){
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();
    System.out.println("Now give me the operation (+,-,*,/): ");
    a.nextLine();
    String b = a.next();
    if (b.equals("+")){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (b.equals("-")){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (b.equals("*")){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
    }
hung34k
  • 195
  • 14