如何实现Scanner的自由使用

huangapple go评论66阅读模式
英文:

How to implement discretionary use of Scanner

问题

我是Java的新手,所以如果这显得很简单,我提前道歉。但是,我有一个简单的计算器,按照每个物品“a”的价格为每个物品“b”美元打印成本,但是如果你有超过“c”的物品,那么它的成本是“d”美元。对应的代码如下:

Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt(), d = sc.nextInt();

if (a < b){
    System.out.printf("%d", a * c);
}
if (a == b){
    System.out.printf("%d", a * c);

}
if (a > b){
    System.out.printf("%d", a * d);
}

但我想增加一些灵活性并避免歧义,也就是说,用户输入类似 a=10 b=5 c=4 d=10b=5 d=10 a=10 c=4(或任何组合),都在一行上进行,输出都为 100。因此,我的问题是,如何使用户输入变量的顺序是任意的,同时保持相同的功能?

谢谢。

英文:

I'm a Java newbie, so I apologize in advance if this is trivial. But, I have a simple calculator that prints the cost of 'a' items by 'b' dollars, but if you have more than 'c' items, then it costs 'd' dollars. The code for that is:

Scanner sc = new Scanner(System.in);
    int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt(), d = sc.nextInt();

    if (a &lt; b){
        System.out.printf(&quot;%d&quot;, a * c);
    }
    if (a == b){
        System.out.printf(&quot;%d&quot;, a * c);

    }
    if (a &gt; b){
        System.out.printf(&quot;%d&quot;, a * d);
    }

but I'd like to add a bit more flexibility and avoid ambiguity, that is, the user inputs something like a=10 b=5 c=4 d=10 or b=5 d=10 a=10 c=4 (or any combination) all on one line, and the output is 100 for both. So, my question is how can I make it so that the order in which the user inputs the variables is arbitrary, all whilst keeping the same functionality?

TIA

答案1

得分: 1

你可以按照以下方式进行操作:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入数值:");
        String input = scanner.nextLine(); // 扫描整行输入

        // 使用空白字符拆分输入
        String[] parts = input.split("\\s+");

        // 创建一个带有部分的映射
        Map<String, Integer> map = new HashMap<>();
        for (String part : parts) {
            // 在'='处拆分
            String[] tokens = part.split("=");
            map.put(tokens[0], Integer.valueOf(tokens[1]));
        }

        // 下面的处理与您已经在做的类似
        if (map.get("a") < map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("c"));
        }
        if (map.get("a") == map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("c"));
        }
        if (map.get("a") > map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("d"));
        }
    }
}

示例运行:

输入数值:
a=10 b=5 c=4 d=10
100

另一个示例运行:

输入数值:
b=5 d=10 a=10 c=4
100

注意: 这个解决方案是为了引导您的进展。还有很多工作要做(例如验证、异常处理等),以使其更好。

英文:

You can do something like as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scannner = new Scanner(System.in);
System.out.println(&quot;Enter the values: &quot;);
String input = scannner.nextLine();// Scan the complete line
// Split the input on whitespace
String[] parts = input.split(&quot;\\s+&quot;);
// Create a Map with parts
Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
for (String part : parts) {
// Split on &#39;=&#39;
String[] tokens = part.split(&quot;=&quot;);
map.put(tokens[0], Integer.valueOf(tokens[1]));
}
// The following processing is similar to what you are already doing
if (map.get(&quot;a&quot;) &lt; map.get(&quot;b&quot;)) {
System.out.printf(&quot;%d&quot;, map.get(&quot;a&quot;) * map.get(&quot;c&quot;));
}
if (map.get(&quot;a&quot;) == map.get(&quot;b&quot;)) {
System.out.printf(&quot;%d&quot;, map.get(&quot;a&quot;) * map.get(&quot;c&quot;));
}
if (map.get(&quot;a&quot;) &gt; map.get(&quot;b&quot;)) {
System.out.printf(&quot;%d&quot;, map.get(&quot;a&quot;) * map.get(&quot;d&quot;));
}
}
}

A sample run:

Enter the values: 
a=10 b=5 c=4 d=10
100

Another sample run:

Enter the values: 
b=5 d=10 a=10 c=4
100

Note: This solution is to guide you progress. There is a lot to be done (e.g. validations, exception handling etc.) in order to make it better.

答案2

得分: 1

尝试这个

    import java.util.Scanner;
    
    public class SimpleCalculatorScanner {
        public static void main(final String[] args) {
            Scanner sc = new Scanner(System.in);
            String[] variables = sc.nextLine().split(" ");
            int a = 0;
            int b = 0;
            int c = 0;
            int d = 0;
            for(int i = 0; i < variables.length; i++) {
                try {
                    if(variables[i].substring(0, 2).equals("a=")) {
                        a=Integer.parseInt(variables[i].substring(2));
                    }else if(variables[i].substring(0, 2).equals("b=")) {
                        b=Integer.parseInt(variables[i].substring(2));
                    }else if(variables[i].substring(0, 2).equals("c=")) {
                        c=Integer.parseInt(variables[i].substring(2));
                    }else if(variables[i].substring(0, 2).equals("d=")){
                        d=Integer.parseInt(variables[i].substring(2));
                    }else {
                        System.out.println("无法识别的变量 "+variables[i].substring(0, 1)+" 检测到");
                        return;
                    }
                }catch(NumberFormatException e) {
                    System.out.println("你分配给变量 "+variables[i].substring(0, 1)+" 的字符不是一个数字");
                    return;
                }
            }
            if (a < b){
                System.out.printf("%d", a * c);
            }
            if (a == b){
                System.out.printf("%d", a * c);
            }
            if (a > b){
                System.out.printf("%d", a * d);
            }
        }
    }

**示例输入/输出**

*输入*

    b=5 d=10 a=10 c=4

*输出*

    100

*输入 2*

    b=5 d=10 e=10 c=4

**输出 2**

    无法识别的变量 e 检测到

*输入 3*

    a=10 b=5 c=4 d=iforgot

*输出 3*

    你分配给变量 d 的字符不是一个数字

**工作原理**

Scanner读取一行然后通过分割每个空格将其转换为数组

一旦变量被存储到数组中我们运行一个**for**循环来测试数组中每个项的前两个字符是否为`a=`、`b=`、`c=``d=`。如果是`a=`,则将`=`后的每个字符解析为整数并将其赋值给变量a依此类推

如果它无法识别变量它将打印出`无法识别的变量 <variablename> 检测到`。

如果分配给变量的字符不是数字它将打印出`你分配给变量 <variablename> 的字符不是一个数字`。
英文:

Try this:

import java.util.Scanner;
public class SimpleCalculatorScanner {
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
String[] variables = sc.nextLine().split(&quot; &quot;);
int a = 0;
int b = 0;
int c = 0;
int d = 0;
for(int i = 0; i &lt; variables.length; i++) {
try {
if(variables[i].substring(0, 2).equals(&quot;a=&quot;)) {
a=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals(&quot;b=&quot;)) {
b=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals(&quot;c=&quot;)) {
c=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals(&quot;d=&quot;)){
d=Integer.parseInt(variables[i].substring(2));
}else {
System.out.println(&quot;Unrecognized variable &quot;+variables[i].substring(0, 1)+&quot; detected&quot;);
return;
}
}catch(NumberFormatException e) {
System.out.println(&quot;The character you assigned to variable &quot;+variables[i].substring(0, 1)+&quot; isn&#39;t a number&quot;);
return;
}    		}
if (a &lt; b){
System.out.printf(&quot;%d&quot;, a * c);
}
if (a == b){
System.out.printf(&quot;%d&quot;, a * c);
}
if (a &gt; b){
System.out.printf(&quot;%d&quot;, a * d);
}
}
}

Sample I/O

Input

b=5 d=10 a=10 c=4

Output

100

Input 2

b=5 d=10 e=10 c=4

Output 2

Unrecognized variable e detected

Input 3

a=10 b=5 c=4 d=iforgot

Output 3

The character you assigned to variable d isn&#39;t a number

How it works

The Scanner reads a new line, and then turns it into an array by splitting every space.

Once the variables have been stored into an array, we run a for loop to test whether the first 2 characters of each item of the array are a=, b=, c= or d=. If it is a=, then it parses the every character after the = of the item in the array into an integer, and assigns it to variable a, vice versa.

If it doesn't recognize the variable, it will print Unrecognized variable &lt;variablename&gt; detected.

If the character assigned to the variable wasn't a number, it will print The character you assigned to variable &lt;variablename&gt; isn&#39;t a number

huangapple
  • 本文由 发表于 2020年9月19日 03:31:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63961766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定