问题是这样的:
EG。 abbccc是超级ascii,因为a = 1,b = 2,c = 3。同样地,bab," bb a ccc"
这是我尝试解决问题
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class SuperAsciiNew
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
String input = in.nextLine();
char[] inputArray = input.replaceAll("\\s+","").toCharArray();
Arrays.sort(inputArray);
String customInput = new String(inputArray);
char currentChar = customInput.charAt(0);
int increment=0;
Map<Character, Integer> characterMap = new HashMap<Character, Integer>();
char a='a';
boolean superascii = true;
for(int i=1;a<='z';i++,a++)
characterMap.put(new Character(a), new Integer(i));
while(increment<=customInput.length())
{
int nooftimes = customInput.lastIndexOf(currentChar) - customInput.indexOf(currentChar) + 1;
if(characterMap.get(currentChar) == nooftimes)
{
System.out.println("The character "+currentChar+" is repeated "+nooftimes);
increment += nooftimes;
currentChar = customInput.charAt(increment);
}
else
{
superascii = false;
break;
}
}
if(superascii == true)
System.out.println("The given string "+input+" is a Super Ascii string");
else
System.out.println("The given string "+input+" is not a Super Ascii string");
}
}
这里,首先我删除空格(如果有的话),对字符串进行排序。然后,我找到字符串中的第一个字符,它的值是什么以及它重复了多少次。如果这两个值不相等则循环中断,则重复字符的次数以递增变量递增,并找到下一个字符。
我得到的各种测试用例的输出:
java SuperAsciiNew
Enter a string : abb ccc
The character a is repeated 1
The character b is repeated 2
The character c is repeated 3
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : bab
The character a is repeated 1
The character b is repeated 2
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at SuperAsciiNew.main(SuperAsciiNew.java:30)
java SuperAsciiNew
Enter a string : hello world
The given string hello world is not a Super Ascii string
当字符串&#34; hello world&#34;给出,输出生成没有任何例外。这是什么问题?
我在Java中还有一个疑问:
答案 0 :(得分:1)
您正在检查一个角色太多次。 使用以下条件:
while(increment<=customInput.length()-1)
而不是:
while(increment<=customInput.length())
编辑:你没有在“hello world”上收到错误的原因是因为它在到达那个额外的char之前失败了,因此没有抛出异常。