使用charAt方法,不会将它们添加为Int,也不会打印为字符串。 会解释得更好

好的,所以这是我的代码:

import java.util.Scanner; public class CarRental { public static String model; public static int letternum; public static String plate; public static String letter; public static int total; public static String alphabet = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { Scanner input = new Scanner(System.in); //System.out.println("Car Model:"); //model = input.nextLine(); System.out.println("License Plate: "); plate = input.nextLine(); char one = plate.charAt(0); char two = plate.charAt(1); char three = plate.charAt(2); total = one + two + three; letternum = total % 24; char letter = alphabet.charAt(letternum); System.out.println("" + letter + total); } } 

这是怎么回事,我试图让我的牌照输入并取出0,1和2处的角色。牌照中的三个字母。 然后,我试图获取他们的ASCII值,将它们全部加在一起并将它们设置为int“total”。 然后要找到一个应该在总值之前的字母,我通过使用%6找到总数的剩余部分。然后它将取该值,无论它是多少,说它是4,它将需要字符串“alphabet”中的第四个字母,并将其设置为char“letter”。 那么它应该做的是打印出字母后跟ASCII值的总和。

以下是我对预期结果的输入,然后是其实际结果的示例。

车牌:CPR 607

输出:E836

我的输出与完全相同的车牌是:

车牌:CPR 607

n229

我不确定我做错了什么,但我最好的线索是它是一个char的事实,它将它视为它的ASCII值,而不是它的String值(我实际上试图得到它)

如果有人可以提出一些提示,那将是一个很大的帮助。 不一定是我可以躲开的代码,但我应该如何以正确的方式做到这一点!

你想获取字符串的第二部分(带有三个数字)并将其添加到总数中。 您可以使用以下值:

Integer.parseInt(plate.split(“”)[1])

改变这些行:

 int one = (int) plate.charAt(0); int two = (int) plate.charAt(1); int three = (int) plate.charAt(2); 

这将为您提供字符的实际ASCII值。

如果你想要别的东西,你必须从每个值中减去一个常量,正如jonhopkins在他的评论中所说明的那样。

减去64得到A = 1,B = 2等。

我看到你的问题。

该算法采用前3个字符的ASCII值并将它们添加到数字 (最后3个字符)。

此外,您必须除以6才能得到字母A – E.您将除以24。

如果你将229的值添加到牌照中的607,你会得到你说你应该得到的836号码,所以看起来你的总变量是正确的,但你只需要将它添加到号码中从输入。

其他人都在谈论转移ASCII值的原因是当你确定输出中的第一个字符时。

 public static String model; public static int letternum; public static String plate; public static String letter; public static int total; public static String alphabet = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { Scanner input = new Scanner(System.in); //System.out.println("Car Model:"); //model = input.nextLine(); System.out.println("License Plate: "); plate = input.nextLine(); char one = plate.charAt(0); char two = plate.charAt(1); char three = plate.charAt(2); total = Integer.parseInt(one) + Integer.parseInt(two) + Integer.parseInt(three); letternum = total % 24; char letter = alphabet.charAt(letternum); System.out.println("" + letter + total); } 

你忘了把它变成整数