java - 如何将用户输入添加到我的 Java 程序中以便在 if 语句中使用

标签 java if-statement int

我正在尝试将用户输入添加到我的类中,以便用户可以输入他们的包裹的重量,我的类会告诉他们需要花费多少钱。我对java很陌生,所以我知道这并不令人惊奇,但这是我目前能做的最好的事情。提前致谢

public class ShippingCosts {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int weight = 0;

        if (0 < weight && weight <= 1)
            System.out.println("The cost to ship the package is $3.50");
        if (1 < weight && weight <= 3)
            System.out.println("The cost to ship the package is $5.50");
        if (3 < weight && weight <= 10)
            System.out.println("The cost to ship the package is $9.50");
        if (10 < weight && weight <= 20)
            System.out.println("The cost to ship the package is $13.50");
        if (20 < weight)
            System.out.println("The package is too heavy to be shipped");

        System.out.println("How heavy is the package?");

    }

}

最佳答案

简单的例子是这样的: 尝试在文档中阅读更多相关信息 Java Scanner

// read a number from System.in:
    Scanner scan = new Scanner(System.in);
    String s = scan.next();
    int i = scan.nextInt(); //read integers

> public String next()  --->it returns the next token from the scanner.

> public String nextLine()--->  it moves the scanner position to the next line and returns the value as a string. 

> public byte nextByte() --->it scans the next token as a byte. 

> public short nextShort() --->it scans the next token as a short value.

> public int nextInt() --->it scans the next token as an int value. 

> public long nextLong() --->it scans the next token as a long value. 

> public float nextFloat() --->it scans the next token as a float value. 

> public double nextDouble() --->it scans the next token as a double value.

提示用户输入:

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name : "); //prompt user
s = input.next(); // getting a String value

System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer

System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double

关于java - 如何将用户输入添加到我的 Java 程序中以便在 if 语句中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288101/

相关文章:

java - LocalDateTime 解析错误(Java 8)

当用户输入句点时停止的 Java 计算器程序

c++ - 我怎样才能在我的罗马数字到十进制转换器中得到结果?

java - 递归必须解析为类型,但我不知道如何构造它?

java - 在一个类中使用 String/int/long 等

java - 根据当前API实现接口(interface)

ios - 如果字符串包含语句 - Swift 2 Xcode 7

ios - 从方法内部获取函数数据(包括简单代码)

c - 如何正确地将十进制 MIDI 弯音值分成 2 个分开的 7 位值?

java - 从匿名内部 "runnable"类中调用方法。这是不好的做法吗?