简体   繁体   English

java IF语句不适合我,我的变量有问题

[英]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”或“l”,则会生成一条消息。 If 'M' or 'l' has been inputted then the answer (4 or 5) should be displayed. 如果输入“M”或“l”,则应显示答案(4或5)。

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. 每当我输入一个字母时弹出一个错误,如果我输入任何数字“比萨大小必须是M(中)或l(大):”弹出消息。 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: 为了能够要求用户输入M或L,如果以前的输入错误,请使用以下代码:

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(); 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. 将变量类型的fstep更改为string,并使用pizzasize.next()为其分配字母。

Also if you want to compare letters better to do string comparison in if statement rather than the number comparison you have done 另外,如果你想更好地比较字母以在if语句中进行字符串比较而不是你已经完成的数字比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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