Hanging Letter Program - java

I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.

First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t

Related

How to Find the word that comes after a specified word in java String

My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.

Working Sturcture of Arrays. binarySearch() method in java

I'm trying solve problem in Strings,finding matching characters in to String.
I solve it using Character Array and inner loop but i think it has more time complexity. so try to solve it in Arrays binary search but it gives inappropriate result.i want working structure of binary search method in java.
I set matched value in the String two to duplicate char '#',because don't want to match another char.
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
String team1 = s.next();
String team2 = s.next();
char[] teamA = team1.toCharArray();
char[] teamB = team2.toCharArray();
Arrays.sort(teamB);
int count = 0;
for(int a=0;a< teamA.length;a++) {
int index = Arrays.binarySearch(teamB, teamA[a]);
if(index >= 0) {
count++;
teamB[index] = '#';
}
}
System.out.println(count);
}
if i give input of two strings
"aabc" and "zbaa" expected output is 3
but my program gives output 2.
The problem is that once you update the teamB array in the loop the array is no longer sorted. And in unsorted array binary search will give unexpected outputs.

Java Word Count

I am just starting out in Java so I appreciate your patience. Anyways, I am writing a word count program as you can tell by the title, I am stuck at the numWords function below the for loop, I am not sure what I should set it equal to. If someone could set me in the right direction that would be awesome. Thank you. Here is all of my code thus far, let me know if I not specific enough in what I am asking, this is my first post. Thanks again.
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s\
+");
for(int i = 0; i < words.length; i++){
numWords = 0;
}
}
}
}
If your code is intended to just count words, then you don't need to iterate through the words array at all. In other words, replace your for loop with just:
numWords += words.length;
Most likely a simpler approach would be to look for sequences of alpha characters:
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find())
numWords++;
If you need to do something with the words (such as store them in a map to a count) then this approach will make that simpler:
Map<String,Integer> wordCount = new HashMap<>();
Matcher wordMatch = Pattern.compile("\\w+").matcher();
while (wordMatch.find()) {
String word = wordMatch.group();
int count = wordCount.getOrDefault(word, 0);
wordCount.put(word, count + 1);
}
Don't worry. We were all beginners once.
First of all, you don't need to do the loop because "length" attribute already has it. But, if you want to practice with loops is so easy as increasing the counter each time the iterator advances and that's it.
numWords++;
Hint: Read the input
String sentence = stdin.nextLine();
Split the string
String [] words = sentence.split(" ");
Number of words in a sentence
System.out.println("number of words in a sentence are " + words.length);
You mentioned in comments that you would also like to print the line in alphabetical order. For that Java got you covered:
Arrays.sort(words);
The best way to count the amount of words in a String String phrase is simply to get a String array from it using the String method split String[] words = phrase.split(" ") and giving it as argument the space itself, this will return a String array with each different words, then you can simple check its lengthwords.length and this will give you the exact number.

Java String output limiting range of String to Alphabet

I'm currently doing an exercise(not homework before anyone gives out) and I am stuck in the final part of the question.
The question is:
Write a program which will input a String from the keyboard, output the number of
seperate words, where a word is one or more characters seperated by spaces. Your
program should only count words as groups of characters in the rang A..Z and a..z
I can do the first part no problem as you can see by my code:
import java.util.Scanner;
public class Exercise10 {
public static void main(String[] args) {
String input;
int counter = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your text: ");
input = keyboard.nextLine();
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' '){
counter++;
}
}
System.out.println(counter + 1);
keyboard.close();
}
}
However the part that is confusing me is this:
Your program should only count words as groups of characters in the rang A..Z and
a..z
What should I do in this instance?
I won't give you a full answer but here are two hints.
Instead of counting spaces look at splitting the string and looping through each element from the split:
Documentation
Once you have the String split and can iterate through the elements, iterate through each character in each element to check if it is alphabetic:
Hint
I believe it should not consider separate punctuation characters as words. So the phrase one, two, three ! would have 3 words, even if ! is separated by space.
Split the string on spaces. For every token, check the characters; if at least one of them is in range a..z or A..Z, increment counter and get to the next token.

How can I reverse individual words in a string while using a stack?

I am new to programming and I'm taking a beginner level programming class. I've tried looking around for my answer and I've found results that may work, but I don't understand how to implement them while using a stack. I'm attempting to reverse a string's individual words without reversing the entire string.
For example: the user inputs the sentence "Pies are great!" and I need the output to be "seiP era !taerg"
So far I've managed to write a program that will reverse a string in its entirety, so the output using the above example is: "!taerg era seiP" As you can see, I want to reverse the words themselves without reversing the order of the words, but I must take input using a stack.
The following is what I have so far:
public class ReversedString{
private static ArrayStack<String> stack;
public static void main(String[] args) {
stack = new ArrayStack<String>();
String string = "";
String stringReversed = "";
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the string that you want to reverse: ");
string = scanner.nextLine();
string.split(" ");
for(int i=0; i<string.length(); i++){
stack.push(string.substring(i, i+1));
}
while(!stack.isEmpty()){
stringReversed += stack.pop();
}
System.out.println("The reverse of the string is: " + stringReversed);
read character
while character is whitespace
// do nothing to skip multiple whitespaces.
read character
while character is not whitespace
push character onto stack
read character
// Just read a word, so now dump it back out.
while stack is not empty
ch = pop stack
print ch
Obviously this needs to be in a loop to do multiple words.
Sample implementation of read character
int index = 0;
String theString = "Pies are great!"
char readCharacter()
{
// TODO: needs error checking so you don't run off the end of the string.
char ch = theString.charAt(index);
index++;
return ch;
}
Split the sentence with white-space(" ") like String#split you will get the splitted string which will be words ("Pies", "are", "great!") and then push that into stack and pop the value individually.
String str ="Pies are great!";
String[] strs = str.split(" "); // "Pies", "are", "great!"
String newStr = "";
for(String str1:strs){
//push str1
// pop str1 and add it to newStr
}
Take the code you've already written to reverse a whole String using a stack, and convert it into its own method. Your stack is useful for retrieving letters in reverse order (Last In First Out). Something like:
public String reverse(String str) {
. . .
}
In your main method, split your String into multiple words, and pass each word to your reverse method iteratively. Don't use a stack for your words. Your words are FIFO, and a stack provides LIFO.
try
Scanner sc = new Scanner("Pies are great!");
while(sc.hasNext()) {
System.out.print(new StringBuilder(sc.next()).reverse() + " ");
}
output
seiP era !taerg
or with java.util.Stack
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner("Pies are great!");
while (sc.hasNext()) {
Stack<Character> st = new Stack<>();
for (char c : sc.next().toCharArray()) {
st.push(c);
}
while (!st.isEmpty()) {
sb.append(st.pop());
}
sb.append(' ');
}
System.out.print(sb);
output
seiP era !taerg

Categories