import java.io.*;
import java.util.*;
public class Solution {
public static final int n = 26;
public int check(String arr) {
if (arr.length() < n) {
return -1;
}
for (char c = 'A'; c <= 'Z'; c++) {
if ((arr.indexOf(c) < 0) && (arr.indexOf((char)(c + 32)) < 0)) {
return -1;
}
}
return 1;
}
}
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
String s = s1.next();
Solution obj = new Solution();
int d = obj.check(s);
if (d == -1) {
System.out.print("not pangram");
} else {
System.out.print("pangram");
}
}
如果输入的字符串是:
我们迅速评审了古董象牙扣作为下一个奖项。
它将给出错误的输出:
不是pangram。
我找不出密码出了什么问题。
提前感谢!
发布于 2015-03-20 18:44:37
问题是空白是Scanner.next()
的分隔符。因此,当您输入We promptly judged antique ivory buckles for the next prize
时,s
只会指向字符串We
。当您在obj.check(s)
上调用We
时,它将返回-1
。
要验证是否存在这种情况,可以打印s
并检查其值。你也可以:
String s = "We promptly judged antique ivory buckles for the next prize";
调用obj.check(s)
并确保它将返回正确的答案。
要解决这个问题,您应该调用Scanner.nextLine()
而不是Scanner.next()
String s = s1.nextLine();
发布于 2015-09-12 13:32:10
May be program by using set will make solution easier ..:)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Pangram {
public static void main(String args[]) {
try {
final String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str = br.readLine().toLowerCase().replaceAll(" ", "");
char[] chars = str.toCharArray();
final Set set = new HashSet();
for(char c: chars){
set.add(c);
}
System.out.println(set.size());
if(set.size() == 26)
System.out.println("pangram");
else
System.out.println("not pangram");
} catch (Exception e) {
e.printStackTrace();
}
}
}
发布于 2016-06-29 11:21:23
另一个版本:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String sentence = scan.nextLine();
sentence = sentence.toUpperCase();
sentence = sentence.replaceAll("[^A-Z]", "");
char[] chars = sentence.toCharArray();
Set<Character> set = new HashSet<Character>();
for( int i = 0; i < chars.length; i++ ) set.add(chars[i]);
System.out.println(set.size() == 26 ? "pangram" : "not pangram");
}
}
https://stackoverflow.com/questions/29173540
复制相似问题