提问者:小点点

在for循环中转换坡度


我有以下代码:

public static void main(String[] args) {
        convert13to7(7);

    }

    public static int convert13to7(int grade) {
        int newGrade = 0;
        int[] scale13 = {00, 03, 5, 6, 7, 8, 9, 10, 11, 13};
        int[] scale7 =  {-3, 00, 00, 02, 4, 7, 7, 10, 12, 12};

        for (int i = 0; i < scale13.length; i++) {
            if (grade == scale13[i]) {
            newGrade = scale7[i];
            }
        }
    return newGrade;
    }

这段代码的目的是将旧的丹麦等级转换成新的等级,但问题是当使用< code>convert13to7函数时,我没有得到任何输出。有人看到这里的问题了吗?


共3个答案

匿名用户

convert13to7生成一个转换后的值,它不会打印它。

System.out.println(convert13to7(7));

其他小问题:

>

  • 方法名称不清楚。
  • 您不一定需要在每次调用方法时初始化这两个数组。
  • 考虑验证。如果您未能转换输入,则返回0不是一个好的选择。

    想想List.indexOf。它更简单、更直观。

  • 匿名用户

    要打印结果,请使用< code > system . out . println():

    int grade = convert13to7(7);
    System.out.println(grade);
    

    我建议您使用< code>Map,而不是每次迭代一个数组:

    public final class GradeConverter {
    
        private final Map<Integer, Integer> map13to7 = new HashMap<>();
    
        {
            map13to7.put(0, -3);
            map13to7.put(3, 0);
            map13to7.put(5, 0);
            map13to7.put(6, 2);
            map13to7.put(7, 4);
            map13to7.put(8, 7);
            map13to7.put(9, 7);
            map13to7.put(10, 10);
            map13to7.put(11, 12);
            map13to7.put(13, 12);
        }
    
        public int convert10to7(int grade) {
            return map13to7.getOrDefault(grade, 0);
        }
    
    }
    

    下一点,注意写03而不是3,因为在Java中,前缀是八进制的标记。E、 g.077是十进制值63

    匿名用户

    您需要在调用方法的地方收集输出。

    package com;
    
    public class Test{
        public static void main(String[] args) {
            // collect output here
            int newGrade = convert13to7(7);
            System.out.println(newGrade);
        }
    
        public static int convert13to7(int grade) {
            int newGrade = 0;
            int[] scale13 = {00, 03, 5, 6, 7, 8, 9, 10, 11, 13};
            int[] scale7 =  {-3, 00, 00, 02, 4, 7, 7, 10, 12, 12};
    
            for (int i = 0; i < scale13.length; i++) {
                if (grade == scale13[i]) {
                newGrade = scale7[i];
                }
            }
            // alternatively you can print output here
            System.out.println(newGrade);
        return newGrade;
        }
    
    }