简体   繁体   中英

java IF statement not working for me, and I an having trouble with my variables

Hello I am trying to produce an If statement that produces a message if a user doesnt input 'M' or 'l'. If 'M' or 'l' has been inputted then the answer (4 or 5) should be displayed.

Whenever I input a letter an error pops up and if i input any number "Pizza size must be M (medium) or l (large):" message pops up. I want the to only input letters not numbers.

apologies if i havent explained the question correctly.

public static void main(String args[]) {

    char invalid;

    double M, l;    

    Scanner pizzasize = new Scanner(System.in);

    double fstep = 0, sstep = 0, tstep = 0, ostep = 0, lstep = 0;   
    M = 4;
    l = 5;
    System.out.println("Enter pizza size:");

    fstep = pizzasize.nextDouble();

    if(fstep != M|| fstep != l ){
        System.out.println("Pizza size must be M (medium) or l (large):");
    }else{
        String input = pizzasize.next();
        if(fstep == M||fstep ==l){
            fstep = M;
        }
        else if(input.equals("l")){
            fstep = l;
        }

    pizzasize.close();

}

} }

To be able to ask user to input M or L if previous input was wrong use this code:

package com.stackoverflow.json;

import java.util.Scanner;

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

        System.out.println("Enter pizza size:");

        String input = pizzasize.next();

        while (!(input.equals("M") || input.equals("l"))) {
            System.out.println("Pizza size must be M (medium) or l (large):");
            input = pizzasize.next();
        }
        System.out.println(input);
        pizzasize.close();

    }

}

Prints:

Enter pizza size:
a
Pizza size must be M (medium) or l (large):
M
M

fstep = pizzasize.nextDouble();

You are requesting the scanner to read a double value here which is why it gives an error when you input letters.

Change variable type of fstep to string and use pizzasize.next() to assign letters to it.

Also if you want to compare letters better to do string comparison in if statement rather than the number comparison you have done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM