找到两个字母之间的距离

时间:2016-10-08 14:51:19

标签: java

在这个问题中,需要找到两个字母之间的距离 例如。在A和E之间,字母是B,C,D.So,字母之间的距离是字母数+ 1,即4,这里。但我没有得到此代码的输出

     import java.util.*;
     public class Main{
        public static void main(String args[]){
        String s1,s2;
        Scanner input=new Scanner(System.in);
        input.nextLine();
        s1=input.nextLine();
        input.nextLine();
        s2=input.nextLine();
       int result=((int)s2.toLowerCase().charAt(0)-(int)s1.toLowerCase().charAt(0))+1;
        result=Math.abs(result);
        System.out.println(result);

    }
}

2 个答案:

答案 0 :(得分:0)

您有额外的nextLine方法调用。修改了您的代码以使其正常工作。

import java.util.Scanner;

public class LetterDistance {

    public static void main(String[] args) {

        String s1, s2;
        Scanner input = new Scanner(System.in);
        s1 = input.nextLine();
        s2 = input.nextLine();
        int result = ((int) s2.toLowerCase().charAt(0) - (int) s1.toLowerCase()
                .charAt(0)) + 1;
        result = Math.abs(result);
        System.out.println(result);

    }

}

答案 1 :(得分:0)

Scanner input = new Scanner(System.in);

System.out.print("Write 1. character: ");
String s1 = input.nextLine();
System.out.print("Write 2. character: ");
String s2 = input.nextLine();

String alphabet = "abcdefghijklmnopqrstuvwxyz";

int s1no = alphabet.indexOf(s1);
int s2no = alphabet.indexOf(s2);

if (s1no > s2no)
 System.out.println("Distance: " + (s1no - s2no));
else
 System.out.println("First character must be bigger than second character");