-4

I am trying to make a sort of ATM. I want the program to do the following: If a user enters a number, the number gets multiplied by 12.

I already have the following code:

import java.util.Scanner;

public class DisplayMultiples {

    public static void main(String args[]) {


        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Enter a number between 1 and 12 ");
        keyboardInput.nextLine();  

        int b = 12;

        if() {
        for (int i = 1; i < b; i++) {

            System.out.println(i*b);


            }
        else {
             System.out.println("Error, this value is never used");
                }
        }
    }
letsintegreat
  • 3,328
  • 4
  • 18
  • 39

3 Answers3

1
  1. Convert the input to a number.
  2. If the input is not a number, show error message, and exit.
  3. If the input is a number, multiply it by 12, show result, and exit.
m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

The easiest way is to get an int from the Scanner and then check if it's between 1 and 12, and if so, multiply it by 12.

Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
int number = keyboardInput.nextInt();
if (number > 0 && number < 13) {
    System.out.println(number * 12);
} else {
    System.out.println("Error, this value is never used");
}

Note that as you are likely a beginner, entering anything but an int in the console will result in an error but I assume that's not entirely necessary for you. If it is, read up on try...catch.

achAmháin
  • 4,176
  • 4
  • 17
  • 40
-1

This way will avoid exceptions when entering non numbers.

    Scanner keyboardInput = new Scanner(System.in);
    System.out.println("Enter a number between 1 and 12 ");
    String inpStr = keyboardInput.nextLine();
    int b = 12;
    int inpVal = -1;

    try {
        inpVal = Integer.parseInt(inpStr);
    } catch (NumberFormatException nfe) {

    }

    if (inpVal >= 1 && inpVal <= 12) {
        System.out.println(inpVal * b);
    } else {
        System.out.println("Error, this value is never used");
    }
Michael Besteck
  • 2,415
  • 18
  • 10
  • 2
    Never ever have empty catch blocks – m0skit0 Feb 11 '19 at 16:35
  • @m0skit0 Why? Is that your private rule? The code compiles without error, and is working correctly. I expect an explanation. – Michael Besteck Feb 12 '19 at 15:36
  • https://stackoverflow.com/questions/1234343/why-are-empty-catch-blocks-a-bad-idea – m0skit0 Feb 12 '19 at 15:58
  • @m0skit0 Even your quote says "Occasionally this may be the right thing to do". Seems you did not analyse my answer. Any code in the catch block would be redundant, which would be a real bad thing. Your downvote seems not be based on logic and code understanding. – Michael Besteck Feb 19 '19 at 16:10