forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScrabbleString.java
More file actions
65 lines (59 loc) · 1.74 KB
/
ScrabbleString.java
File metadata and controls
65 lines (59 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Scanner;
/**
* Created by Comarch on 2016-07-18.
*/
public class ScrabbleString {
public static String readInput(String paramName){
Scanner in = new Scanner(System.in);
System.out.print("\n Write " + paramName + ": ");
return in.nextLine();
}
/*
* Returns TRUE when input char is in input string
*/
public static boolean isInString(char letter, String word){
boolean okay = false;
for(int i=0; i<word.length(); i++){
if(letter == word.charAt(i)){
okay = true;
break;
}
}
return okay;
}
/*
* Returns input string without input char
*/
public static String removeLetterFromWord(char letter, String word){
int index = 0;
for(int i=0; i<word.length(); i++){
if(letter == word.charAt(i)){
index = i;
break;
}
}
if(index == word.length()-1){
return word.substring(0,index);
} else{
return word.substring(0,index) + word.substring(index+1, word.length()-1);
}
}
public static boolean canSpell(String tiles, String word){
boolean okay = true;
char tmp;
for(int i=0; i<word.length(); i++){
tmp = word.charAt(i);
if(isInString(tmp, tiles)){
tiles = removeLetterFromWord(tmp, tiles);
} else{
okay = false;
}
}
return okay;
}
public static void main(String[] args){
String tiles = readInput("tiles word");
String userWord = readInput("user word");
System.out.print("\nResult: " + canSpell(tiles, userWord));
}
}