[英]Don't understand why my program is running the way that it is
我正在尝试创建一个使用字符数字值(A = 1,B = 2,C = 3 ...)的Java程序。该程序将为用户提供一个单词(即“ BABY”,“ CHILD” ... ),用户可以将字母相减,相乘和相除得到新字母(A + A = B)。
package QUASSINOBALLY;
import java.util.*;
import stdlib.*;
public class YeahBitch {
public static void main(String args[]){
Dictionary<String,Integer> d = new Hashtable<String,Integer>();
ArrayList<String> list = new ArrayList<String>();
list.add("baby");
list.add("child");
list.add("hog");
Random rand = new Random();
String question = list.get(rand.nextInt(list.size()));
question = question.toUpperCase();
System.out.print(question+"\n");
d.put("A",1);
d.put("B",2);
d.put("C",3);
d.put("D",4);
d.put("E",5);
d.put("F",6);
d.put("G",7);
d.put("H",8);
d.put("I",9);
d.put("J",10);
d.put("K",11);
d.put("L",12);
d.put("M",13);
d.put("N",14);
d.put("O",15);
d.put("P",16);
d.put("Q",17);
d.put("R",18);
d.put("S",19);
d.put("T",20);
d.put("U",21);
d.put("V",22);
d.put("W",23);
d.put("X",24);
d.put("Y",25);
d.put("Z",26);
System.out.println("Enter your answer here.");
String answer = StdIn.readString();
answer = answer.toUpperCase();
List<String> operators = new ArrayList<>(Arrays.asList("+", "-","*","/"));
for(int i =0;i<answer.length();i++){
if (!operators.contains(Character.toString(answer.charAt(i)))){
System.out.println("character number:"+i);
System.out.println("character it is now:"+Character.toString(answer.charAt(i)));
System.out.println("character it is going to be:"+d.get(Character.toString(answer.charAt(i))));
answer = answer.replaceFirst(Character.toString(answer.charAt(i)),(d.get(Character.toString(answer.charAt(i))).toString()));
System.out.println(answer);
}
}
System.out.println("Finished!");
}
}
使用打印语句试图帮助调试,并且可能会帮助您调试。
该程序可以运行,但其他时候则不能。
它运行的时间示例:“ a + b + c + d”,“ d + c + b + a”,“ d + c + b + d” ...'
不运行的时间示例:“ b + a + b + y”,“ c + h + i + l + d” ...
程序似乎有多次中断,在“ b + a + b + y”的示例中,字符值为0-6,程序检查元素7并获得值“ 5”。 我已经尝试调试了一段时间,但没有取得太大进展。 代码的特定区域是否过于混乱而无法正常工作? 我希望有提示,而不是有人告诉我明确的答案。
谢谢你的时间。
读写时,字符串中的位置似乎有问题。 在“ CHILD”中,它一直上升到L,因为L = 12,所以它写在两个位置。 然后,而不是读取“ D”,而是读取下一个字符“ 2”,并且由于未定义“ 2”,因此给出了空指针。
这是在运行代码的控制台上得到的:
character number:3
character it is now:L
character it is going to be:12
38912D
character number:4
character it is now:2
character it is going to be:null
Exception in thread "main" java.lang.NullPointerException
您必须跳过两位数的数字才能阅读下一个字母。 这就是为什么对于“ a + b + c + d”,“ d + c + b + a”,“ d + c + b + d”之类的输入正确运行的原因,因为它们的数值小于10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.