如何检查输入的单词是否位于给定“单词范围”的“之前”、“内部”或“之后”?对于每个输入的单词,我们只需要输出 "before", "inside" or "after"
..
判断顺序,字符优先规则为:'' < 'A' < 'a' < 'B' < 'b' .. 'Z' < 'z'
.
Format of input is:
1) <start word> <end word>
2) A sequence of N words
例如:
Input:
============
Apple Pear
Aa
Aq
App
Apple
Output:
============
before // as Aa < Apple
inside // as Aq > Apple && Aq < Pear
before // as App < Apple
inside // as Apple == Apple && Apple < Pear
下面是我得到的,但它给出了错误的输出,所以我的比较逻辑看起来是错误的。
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
String startWord = sc.next(); // this will give "Apple"
String endWord = sc.next(); // this will give "Pear"
while (sc.hasNext()) {
// below will give "Aa", or "Aq", or "App" or "Apple" one by one
String queryWord = sc.next();
if(queryWord.compareTo(startWord) < 0 && queryWord.compareTo(endWord) < 0) {
System.out.println("before");
} else if(queryWord.compareTo(startWord) > 0 && queryWord.compareTo(endWord) > 0) {
System.out.println("after");
} else if(queryWord.compareTo(startWord) == 0 && queryWord.compareTo(endWord) == 0) {
System.out.println("inside");
}
}
sc.close();
}
Update:
那么逻辑会是这样吗?
while (sc.hasNext()) {
String queryWord = sc.next();
int qValue = 0;
for(char c : queryWord.toCharArray()) {
qValue += map.get(c);
}
if(qValue > sValue && qValue < eValue) {
System.out.println("inside");
} else if(qValue > sValue && qValue > eValue) {
System.out.println("before");
} else {
System.out.println("after");
}
}
最佳答案
在发布解决方案之前,让我们看一下输入范围。
单词的每个字母都是 [A,Z] 或 [a-z] 内的任何字母。
下面是我想用来计算给定输入是-before
、inside
还是outside
的逻辑.
1. Let's initialize two variables - startWord and endWord.
2. Take input for the above two variables.
3. Now, I create a map which stores value for each letter constant. As per the question, my values will look something like this:-
A - 1
a - 2
B - 3
b - 4
.
.
Z = 51
z = 52.
4. Now I will calculate value of each word, so for example, value of Apple will be = A+p+p+l+e = 1+32+32+24+10 = 99.
5. Similarly I will do for Pear.
6. Now for each user input value, for example Aa. I will make this calculation again, so for Aa its = A+a = 1+2 = 3. And 3 is less then 99.
7. Now it all comes to Maths, if this value is within the range of startWord and endWord, then I print inside, if its less then answer is before otherwise after.
希望这对您有所帮助!
关于java - 如何根据单词范围检查输入单词的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58017520/