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

Java 为什么我的代码不起作用(日记代码)?,java,Java,这是日记的代码。我希望用户在日记中写些东西,这将是第一页,并将被放在一个列表中。写完后,进入下一页,他在下一页写些东西,等等。 我一次又一次地犯错误,我不知道为什么。在写了“回车”之后,我得到了错误。我对java和所有编程/编码都是新手(如果相同的话)。对不起,如果我问的是一个非常愚蠢的问题:/ 谢谢你的建议。我感谢一切,因为我想在一年内为我的大学尽可能多地学习 import java.util.ArrayList; import java.util.Scanner; public clas

这是日记的代码。我希望用户在日记中写些东西,这将是第一页,并将被放在一个列表中。写完后,进入下一页,他在下一页写些东西,等等。 我一次又一次地犯错误,我不知道为什么。在写了“回车”之后,我得到了错误。我对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)
import java.util.ArrayList;
导入java.util.Scanner;
公共类诺茨布克拉塞酒店{
公共静态无效页(){
System.out.println(“标签1:在你的日记中写点东西。”);
System.out.println(“如果您完成了编写,请输入。”);
ArrayList=新建ArrayList();
字符串列表;
扫描写入;
做{
写入=新扫描仪(System.in);
ListInList=write.next();}
而(!ListInList.equals(“enter”);
System.out.println(“这现在是你的页面,你的页面将
在写了新东西之后创造的。”);
字符串y=列表列表;
列表。添加(y);
write.close();
第()页;
}
公共静态void main(字符串[]Args){
第()页;
}
}
第一天:在日记里写点什么。
如果您已完成写入,请输入。
你好日记
进入
这是您的页面。你的页面将在写了一些东西之后创建
新的。
线程“main”第1天的异常:在日记中写些东西。
如果您已完成写入,请输入。
java.util.NoSuchElementException
位于java.util.Scanner.throwFor(未知源)
位于java.util.Scanner.next(未知源)
位于NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
在NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
main(NotizbuchKlasse.java:38)
a、 nextInt()需要一个“int”,但要传递一个char。 你有两种可能

  • 创建另一个将接受“char”的扫描仪
  • 使用方法“next()”。像这样:a.next(); 在第二种情况下,使用.equals(“您的操作”),因为您无法将字符串与“==”进行比较 您使用的是一个.nextInt(),用于将整数作为输入。只需使用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();
        }
    }
    
    指:

    输入
    +
    后,抛出了
    异常。这是
    输入不匹配异常
    。它是在第30行的Taschenrechrer.java中(…)
    Scanner#nextInt
    中抛出的

    在提供的代码中,还有三个不同的问题。一是你应该区分
    “x”
    '
    。第一个是
    字符串
    ,另一个是
    字符

    另一个事实是,您可能希望使用浮点除法而不是整数,因此必须在除法之前添加
    1.0
    。否则,结果将始终为整数

    但最重要的一点是,扫描仪与输入流相关联。溪流是一种漂浮不倒的东西。这意味着,您必须读取一次输入,然后比较它是什么。调用
    a.next()
    三次将导致扫描仪读取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();
            }
    
    }
    

    首先,在读取运算符号时,需要将其作为字符串读取,因为它不是整数。 此外,在比较字符串时,应使用
    equals
    方法。 最后,在执行除法时,应将其中一个操作数强制转换为浮点以获得浮点结果(否则将获得强制转换的除法-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
      方法比较字符串
    • 如果需要,您可以通过
      开关盒更改
      If
      If else
      else

      • 您的代码中有2个问题

      • 当输入数学时,字符串不能是整数
      • 在比较数学时,必须使用“不使用”字符。因为“字符”有意义字符串和“正意义字符”
      • 所以,请尝试下面的代码

        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();
            }
        

        我将仔细阅读您的代码并提出一些重构建议

         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)
        我只想读一个字符。
        


        我还将方法
        计算器
        重命名为
        计算
        。我非常喜欢干净的代码实践。方法的名称是动词,而类名是名词。

        要获得使用了nextInt的数学运算符

        a、 nextInt()='+'

        这就是问题的原因。 另外,使用switch可以使代码更加健壮和可读。

        它可以工作

        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();
        }
        

        您正在扫描仪实例上调用
        nextInt
        ,但
        +
        不可用。请尝试在此处使用真实的单词-“您”不比“u”更难键入。这使得文章能为广大读者阅读,包括母语不是英语的人。谢谢请注意,
        a.next()
        返回一个
        String
        ,而不是
        charpublic 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();
            }
        }
        
        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();
        }