【问题标题】:How do I add user input into my Java Program for use in if statements [duplicate]如何将用户输入添加到我的 Java 程序中以用于 if 语句 [重复]
【发布时间】:2016-11-12 06:55:23
【问题描述】:

我正在尝试将用户输入添加到我的班级中,以便用户可以输入他们的包裹重量,而我的班级会告诉他们要花多少钱。我对 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?");

    }

}

【问题讨论】:

  • 发帖前请先搜索 Stack Overflow。

标签: java if-statement int


【解决方案1】:

简单的例子是这样的: 尝试在文档中阅读更多相关信息 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.util.Scanner,但我仍然对如何从这里真正获得用户输入感到困惑。当我说我是 Java 新手时,我的意思是我几天前就开始了,所以我需要一段时间才能变得更好。
  • 感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多