So I am a beginner in Java and was solving from a book where the question was :
Write a program that sets up a String variable containing a paragraph
of text of your choice. Extract the words from the text and sort them
into alphabetical order. Display the sorted list of words. You could
use a simple sorting method called the bubble sort. To sort an array
into ascending order the process is as follows: a. Starting with the
first element in the array, compare successive elements (0 and 1, 1
and 2, 2 and 3, and so on). b. If the first element of any pair is
greater than the second, interchange the two elements. c. Repeat the
process for the whole array until no interchanges are necessary. The
array elements are now in ascending order.
To which my solution was:
public class bubbleSort {
public static void main(String[] args) {
String Homer = "He was the son of Epikaste and Telemachus. " +
"He was said to be a court singer ";
String swap;
Homer = Homer.replace(',', ' ');
Homer = Homer.replace('.', ' ');
Homer = Homer.replace(" ", " ");
String[] words = Homer.split(" ");
for(String val:words){
System.out.println(val);
}
System.out.println(" ---- SORTED -------");
boolean exchange = true;
while (exchange) {
exchange = false;
for (int i = 0; i < (words.length - 1); ++i) {
if (words[i].charAt(0) > words[i + 1].charAt(0)) {
swap = words[i];
words[i] = words[i + 1];
words[i + 1] = swap;
exchange = true;
}
}
}
for(String val:words){
System.out.println(val);
}
}
}
However the sorted output wasn't as intended !
He was the son of Epikaste and Telemachus He was said to be a court
singer ---- SORETED ------- Epikaste He He Telemachus and a be court
of son said singer the to was was
Where have I made a mistake? Thanks !
The simple way would be to convert all words to upper or lower case.
However, the correct way to compare words of a language in Java is to use the Collator
Collator myCollator = Collator.getInstance(); // optional: pass your locale
if( myCollator.compare("abc", "ABC") < 0 )
System.out.println("abc is less than ABC");
else
System.out.println("abc is greater than or equal to ABC");
This makes sure that words with special characters like 'è' or 'ä' are sorted correctly. While this makes no difference for your example, if you are learning Java, learn it right from the start.
In your example, create a collator instance at the beginning of the method and replace
if (words[i].charAt(0) > words[i + 1].charAt(0))
with
if (myCollator.compare(words[i], words[i+1]) > 0)
It is sorted Capital letters are less than lower case letters in ascii to get the correct sorting change all the capitals to lower case or vise versa while sorting
I guess what you don't like in the result is that it sorted uppercase (capitalized) words before lowercase words. This is not surprising, because uppercase characters A-Z use the code points 65 through 90, whereas lowercase chars a-z have code points 97 through 122. So uppercase chars are always "smaller" than lowercase chars in a comparision.
Solution: Convert all words to lowercase for the comparison. Use String.toLowerCase() for that.
For example, instead of your original code
for (int i = 0; i < (words.length - 1); ++i) {
if (words[i].charAt(0) > words[i + 1].charAt(0)) {
do it more like
for (int i = 0; i < (words.length - 1); ++i) {
String w = words[i].toLowerCase();
String w1 = words[i+1].toLowerCase();
if (w.charAt(0) > w1.charAt(0)) {
Related
I Have a String S= "I love bangalore " It should print the letters between 2 vowels like below :
1.v
2.ng
3.l
4.r
Note : I am able to print if there only 1 letter b/w 2 vowels not more than that.
This what I have tried :
String a = "i love bangalore";
String[] words = a.split(" ");
for (String word : words) {
for (int i = 1; i < word.length(); i++) {
if (word.length() > 3) {
if(i==word.length()-1){
System.out.println("skip");
}
else if(checkIsVowel(word.charAt(i))&&!checkIsVowel(word.charAt(i+1))&&checkIsVowel(word.charAt(i+2))){
System.out.println(word.charAt(i+1));
}
}
}
}
The way you are trying is not right because
You are checking for length 3 or more which is not true
You are checking for vowel, normal alphabet, vowel which is also not true. ex: angl
Here is one way to solve it
String[] words = str.split(" ");
for (String word : words) {
int firstVowelIndex = -1;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (checkIsVowel(ch)) {
// if vowel index is found again and there exists at least one character between the two vowels
if (firstVowelIndex != -1 && i - firstVowelIndex != 0) {
System.out.println(word.substring(firstVowelIndex + 1, i));
}
// vowel index is assigned
firstVowelIndex = i;
}
}
}
Input:
i love bangalore
Output:
v
ng
l
r
The best way to do this is as follows:
Find a vowel, non-vowel pair.
Set result to non-vowel.
Continue to find non-vowels, appending to result
When a vowel is encountered, either print or save result
remembering you are at a vowel, go back to 1 and repeat until word is exhausted.
Make certain you use print statements to help debug your program.
I have created a program that allows the user to enter 5 words. These words
are stored into a string array. When the user is finished, the number of times a word beginning with the letter ‘B’ was entered, lower or uppercase is displayed. Now I also have to re-state the B words.
So this is the code I have so far that finds how many of the words entered starts with "b"
int fromIndex = 0;
int count = 0;
String words[] = new String [5];
for (int x = 0 ; x <= words.length - 1 ; x = x + 1)
{
System.out.print ("Please enter a word: ");
words [x] = kbi.readLine ();
fromIndex = 0;
words [x] = words [x].toLowerCase ();
fromIndex = words [x].indexOf ("b", fromIndex);
if (fromIndex == 0) // STARTS WITH B
{
count++;
}
}
System.out.println ("You entered " + count + " 'B' words and they were: ");
I was thinking that I could use an if statement to print the b words. Like:
if (words.charAt(0) == "b")
{
System.out.println (words);
}
but that doesn't really seem to work and I didn't really think it would, I'm kind of at a loss of what to do.
I hope I can receive some help on this, thank you in advance.
in your code words is not an String(it is an array of String) so it doesn't have charAt method that you used above. you have 5 String in your words array so if you want to write all String in your array which start with character 'b' you should loop through your array and print all that start with 'b', like this:
for(String str : words){
if (str.charAt(0) == 'b'){
System.out.println(str);
}
some tips:
in java 7 String has startsWith method that you can use. if you are using java 6 check if it has it too:
for(String str : words){
if (str.startsWith("b", 0)){
System.out.println(str);
}
It's because charAt returns char instead of String, so you would have to change your comparison:
if (words.charAt(0) == 'b')
Other possibility would be to use regex "b.*" or even easier - String comes with startsWith method, so you can simply do this:
if (words.startsWith("b"))
14.11 (Searching Strings) Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurrences of the character in the text.
14.12 (Searching Strings) Write an application based on the application in Exercise 14.11 that inputs a line of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.
My problem now is that how can I determine occurrence of each letter in a word. For example, the word "occurrence", how many times each letter occurred in this word.
I've written my code to the best of my understanding, and my code can display the characters and returns their indexes in a tabular form. But that is not exactly what the questions required.
import java.util.*;
public class Searching
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Text: ");
String text1 = input.nextLine();
char[] text2 = text1.toCharArray();
System.out.println("Character Index");
for(int i = 0; i < text2.length; i++)
{
System.out.printf("%s%12d%n", text2[i],text1.indexOf(text2[i], i));
}
}
}
I want the actual output to be in a tabular format. The word "occurrence", my code should display each letter and how many times it occurred.
LETTER FREQUENCY
o 1
c 3
u 1
r 2
e 2
n 1
Is it ok if you used a HashMap? Here's the solution for 14.12:
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
//So we only have to find lower case chars
String input = in.nextLine().toLowerCase();
//Add every single character in the word
//We use a LinkedHashMap instead of a HashMap to retain character order during printing.
LinkedHashMap<Character, Integer> characterCount = new LinkedHashMap<>();
for(int i = 0; i < input.length(); i++) {
characterCount.put(input.charAt(i), 0);
}
//Iterate from every character ranging from a - z
//It would be more ideal to iterate only over the characters
//in the word. But your requirement asked to iterate over the alphabet.
for(int i = 'a'; i <= 'z'; i++) {
//This is the character we are currently searching for
Character searchingFor = (char)i;
int startingIndex = 0; int foundIndex = 0;
//Search for the character in the string FROM a specfic index (startingIndex in this case)
//We update startingIndex to a bigger index in the string everytime we find the character.
while((foundIndex = input.indexOf(searchingFor, startingIndex)) != -1) {
//it must be the index+1 so the next time it checks after the found character.
//without the +1, it's an infinite loop.
startingIndex = foundIndex + 1;
//Update count to the current value + 1
characterCount.put(searchingFor, characterCount.get(searchingFor) + 1);
}
}
//Print the results
for(Character c : characterCount.keySet()) {
System.out.printf("%s%12d%n", c, characterCount.get(c));
}
in.close();
Console output for the word "occurence":
Enter text: occurence
o 1
c 3
u 1
r 1
e 2
n 1
Say I have the string: "Polish". which is indexed as: P=0,O=1, L=2, I=3, S=4, H=5
I want to be able to type something like
" word1.arrangebyindex(051423) "
and have word2 equal PHOSLI
I want to be able to type in any combination of index values and have it rearranged to a new word.
I'm trying to write a program that will rearrange a given word in the following way:
The first character of the word is followed by the last character of the word which is followed by the second character and then the second last character of the word and so on. If the given word has an odd number of characters, then the middle character is repeated again. For example, given the word "mouse" it should be encoded as "meosuu"
I suggest making a hashmap, which allows the user to enter in a letter, which would be the key and a number, which would be the value.
Once you associate all the letters with the number as a key and a value (such as P: 0 and H:5), then you can use your hashmap to create a string based on the numbers given to you.
Break each number down by digits (note that it will be more difficult to implement if a word is associated with a multiple digit number) and add to the string depending on what number you have called.
Here's the hashmap api: https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Just look at the method summary and try those. I doubt you'll need much else out of the rest of the api.
If you use HashMap then key as integer and value should be character because if string = APPLE then 0-A 1-P 2-P 3-L 4-E.
or you should go through this way:
public class ModifiedIndex {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char [] ch = str.toCharArray();
String s ="";
int i=0;
int j = str.length()-1;
if(str.length()%2 == 0)
{
for(int k = 0; k < str.length()/2; k++)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
else
{
for(int k = 0; k < str.length(); k++)
{ if(i<=j)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
}
}
}
This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 9 years ago.
I m inserting a string in my program
String str = " I live in India";
how can in get reversed string of that like
String str ="India in live I"
this is an interview question in my interview. Please any one can help me out in this question
Split it and then add it to a new String in reverse order.
String s = " I live in India";
String[] split = s.split(" ");
String result = "";
for (int i = split.length - 1; i >= 0; i--) {
result += (split[i] + " ");
}
System.out.println(result.trim());
This prints:
India in live I
Although short and straight-forward, this solution is not really effective in terms of time and memory. It somewhat depends on how the input is given (as a String or as something else) and whether we can modify the input in order to save computation resources.
Let's assume the sentence is given as an array of characters and we are allowed to modify it. We can then follow the following approach, which brings linear time (O(n)) and constant (O(1)) memory complexity:
What we will have as input would be:
char[] array = {'I',' ','l','i','v','e',' ','i','n',' ','I','n','d','i','a'};
Let's write a method that takes a char[] array and reverses the elements from start to end in-place:
void reverse(char[] array, int start, int end) {
while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
First, we will reverse the whole array (in-place), using this method.
You can notice that after the reversal the words in the sentence are ordered in the desired (reversed) way. The problem is that each word is reversed:
{'a','i','d','n','I',' ','n','i',' ','e','v','i','l',' ','I'}
Let's now iterate the array from left to the right. We will reverse each word in-place, like we initially reversed the whole array. In order to do that, we need to keep an index (start), telling where does a word start and every time we encounter a space (' ') we will trigger a reverse between start and the character before the space. This way we will keep the desired order of words, but we will also have the characters in the words properly ordered.
The code should be self-explanatory:
void reverseSentence(char[] array) {
int n = array.length;
reverse(array, 0, n - 1);
int start = 0;
for (int i = 0; i < n; i++) {
if (array[i] == ' ') {
reverse(array, start, i - 1);
start = i + 1;
}
}
}
Calling this on the initial array, we get:
{'I','n','d','i','a',' ','i','n',' ','l','i','v','e', ' ','I'}
We can further construct a String out of it, or just print it. In any case, the sentence is reversed as desired.
This has linear complexity (O(n)), because each character is part of a reverse exactly once and is being tested for being a space exactly once.
As for memory-usage, we used only one additional variable (start), which makes the total memory complexity a constant (O(1)).
String str = "I live in India";
String result = "";
String[] words = str.split(" ");
for (int i=words.length-1;i>=0;i--){
result = result + words[i] + " ";
}
result = result.subString(result, 0, result.length-1); // remove the last " "
This code splits the String along the whitespaces, so that you get an array of the words.
Then a for loop iterates through the array from last to first element and appends the words plus a whitespace to the result string. Finally the whitepace after the last word is removed.
try this way
public class test {
public static void main(String args[])
{
String x="i live in india";
String y[]=x.split(" ");
System.out.println(y[3]+" "+y[2]+" "+y[1]+" "+y[0]);
// if the input string is different meaning if the number of words are greater than or less than four then try this way
/*for(int i=y.length-1;i>=0;i--)
{
System.out.print(y[i]+ " ");
}*/
}
}
this is the screenshot to show the output