java 为什么我的代码不起作用(日记代码)?

fcipmucu  于 2023-01-04  发布在  Java
关注(0)|答案(8)|浏览(174)

这是一个日记的代码。我希望用户在日记中写一些东西,这将是第一页,并将被放在一个列表中。写回车后,下一页应该开始,他在下一页写一些东西等。我得到错误一遍又一遍,我不知道为什么。写“回车”后,我得到错误。我是新的java和所有的编程/编码(如果是一样的话)。如果我问的是一个很愚蠢的问题,我很抱歉:/谢谢你的每一个建议。我感谢一切,因为我想为我的大学学习尽可能多的东西,这将是在一年内。

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be 
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();        
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something 
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
bvhaajcl

bvhaajcl1#

首先,当你读操作符号时,你需要把它读成一个字符串,因为它不是一个整数。此外,当比较字符串时,你应该使用equals方法。最后,当执行除法时,你应该把其中一个操作数转换为float以获得一个float结果(否则你将获得转换后的division-int-)。
也就是说,您的代码应该如下所示:

import java.util.Scanner;

public class Taschenrechner {

    public static void calculator() {
        Scanner input = new Scanner(System.in);
        // Read input numbers
        System.out.println("Give me the 2 numbers first: ");
        int x = input.nextInt();
        int y = input.nextInt();

        // Read operation
        System.out.println("Now give me the operation (+,-,*,/): ");
        String operation = input.next();

        // Perform operation
        float result = 0;
        if (operation.equals("+")) {
            result = x + y;
        } else if (operation.equals("-")) {
            result = x - y;
        } else if (operation.equals("*")) {
            result = x * y;
        } else if (operation.equals("/")) {
            // Add float casting to one of the operands to obtain a float result
            result = x / ((float) y);
        } else {
            System.err.println("ERROR: Unrecognised operation " + operation);
        }

        // Print result
        System.out.println("Result: " + result);

        // Close scanner
        input.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}

请注意:

  • 我已经将结果打印移到函数的末尾,因为您正在复制代码。
  • 我为不受支持的操作添加了一个else用例。
  • 使用equals方法比较字符串。
  • 如果需要,您可以将ifif-elseelse更改为switch-case
cedebl8k

cedebl8k2#

Give me the 2 numbers first: 
1
2
Now give me the operation (+,-,*,/): 
+
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Taschenrechner.Operationen(Taschenrechner.java:10)
    at Taschenrechner.main(Taschenrechner.java:30)

意思是:
After inputting + there was an Exception thrown. It's InputMismatchException . It was thrown in (...) Scanner#nextInt in Taschenrechrer.java in line 30.
在提供的代码中,也有三个不同的问题,一个是要区分"x"'',第一个是String,第二个是char
另一个原因是,你可能期望浮点除法而不是整数除法,所以你必须在除法之前加上1.0,否则,结果总是整数。
但最重要的一点是scanner与输入流相关联。流是浮动的,不能后退。这意味着,你必须读取输入一次,然后比较它是什么。调用a.next()三次将导致scanner读取3个不同的输入。

public class Taschenrechner {

    public static void calculator(){
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        String op = a.next();
        if (op.equals("+"){
            float result = x + y;
            System.out.println("result: " + result);
        }
        else if (op.equals("-")){
            float result = x - y;
            System.out.println("result: " + result);
        }
        else if (op.equals("*")){
            float result = x * y;
            System.out.println("result: " + result);
        }
        else{
            float result = 1.0 * x / y;
            System.out.println("result: " + result);
            }
        a.close();
        }

        public static void main(String []args) {
            calculator();
        }

}
9vw9lbht

9vw9lbht3#

我会检查你的代码并提出一些重构的建议。

if (a.nextInt()=='+'){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='-'){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='*'){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
}

如果操作不等于您编码的内容,则每次都读取操作。因此,如果用户希望输入操作**-,则必须首先输入不同于+的操作,然后输入-**。
第二,将硬编码常量移到私有静态字段(或者公共静态字段,如果它们在其他类中使用)是一个很好的实践。
代替if-else,我更喜欢使用switch(用于原语、字符串、枚举)--更好的样式和性能(JVM优化了switch)。
这就是我的代码
塔申雷施纳

public class Taschenrechner {

    private static final char ADD = '+';
    private static final char SUB = '-';
    private static final char MUL = '*';
    private static final char DIV = '/';

    public static void calculate() {
        Scanner reader = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = reader.nextInt();
        int y = reader.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        final char operation = reader.next(".").charAt(0); //See explanation bellow.
        float result = calculateResult(x, y, operation);
        System.out.println("result: " + result);
        reader.close();
    }

    private static float calculateResult(float x, float y, char operation) {
        switch (operation) {
            case ADD:
                return x + y;

            case DIV:
                return x / y;

            case SUB:
                return x - y;

            case MUL:
                return x * y;

            default:
                throw new UnsupportedOperationException(operation + " is not suported."); //Terminate the program with an error. Read about exception handling to understand when it can be used.
        }
    }

    public static void main(String[] args) {
        calculate();
    }
}

final char operation = reader.next(".").charAt(0);我只想读取一个字符。https://stackoverflow.com/a/13942707/4587961
我还将方法calculator重命名为calculate。我是Clean Code实践的忠实粉丝。方法的名称是动词,而类的名称是名词。

ws51t4hk

ws51t4hk4#

您使用的是a.next Int(),它用于将整数作为输入。只需使用a.next().charAt(0)代替它即可。这是有效的

import java.util.Scanner;

public class Taschenrechner {
    public static void calculator() {
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        if (a.next().charAt(0) == '+') {
            float result = x + y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '-') {
            float result = x - y;
            System.out.println("result: " + result);
        } else if (a.next().charAt(0) == '*') {
            float result = x * y;
            System.out.println("result: " + result);
        } else {
            float result = x / y;
            System.out.println("result: " + result);
        }
        a.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}
tcbh2hod

tcbh2hod5#

为了获得数学运算符,您使用了nextInt。
a.下一个整数()=='+'
这就是问题的原因。另外,使用switch使代码更健壮和可读性更强。

qhhrdooz

qhhrdooz6#

会成功

public static void calculator() {
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();

    System.out.println("Now give me the operation (+,-,*,/): ");
    String choice = a.next();
    if (choice.equals("+")) {
        float result = x + y;
        System.out.println("result: " + result);
    }
    if (choice.equals("-")) {
        float result = x - y;
        System.out.println("result: " + result);
    }
    if (choice.equals("*")) {
        float result = x * y;
        System.out.println("result: " + result);
    }
    if (choice.equals("/")) {
        float result = x / y;
        System.out.println("result: " + result);
    }
    a.close();
}
vzgqcmou

vzgqcmou7#

if (a.nextInt()=='+'){
    float result = x + y;
    System.out.println("result: " + result);
}

a.nextInt()期望一个“int”,但是你传递给它的是一个char,你有两种可能。
1.创建另一个扫描仪,该扫描仪将接受“char”
1.使用方法“next()",如下所示:a.next();在第二种情况下,使用.equals(“your operation”),因为你不能用“=="比较字符串。

mv1qrgav

mv1qrgav8#

在你的代码有2个问题
1.当输入数学必须是字符串而不是整数时
1.在比较数学时,一定要用“而不要用”字,因为“字“有意义串,而”只是意义字
所以,请尝试下面的代码

public static void calculator(){
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();
    System.out.println("Now give me the operation (+,-,*,/): ");
    a.nextLine();
    String b = a.next();
    if (b.equals("+")){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (b.equals("-")){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (b.equals("*")){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
    }

相关问题