I started this because I was totally bored but because of this error I have been sitting here since so long and finally decided to take this to stackOverFlow. Here is the code Which I wrote.
I was trying to print characters by skipping 1 index. But when there are duplicates I want to print a space which would differentitate words from big string.
Updated Question: Everything fixed except I cant increase I value more than 1. I commented it in below program. Please look at it.
Let me cut the chase and get to the point. I need this output " Vishnu Vardhan" from this String "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
My only requirement is if the string has two same letters it has to print space. So "aVeIwSjHaNgU [aa] VdAgRjDkHxAmN" the aa in the brackets has to be replaced by space.
It has to be dynamic, if any char is repeated it has to print a space and jump to required next char and print it.
Here is the Updated program. Using help from one of the comments.
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;// Increasing I value by 2 here will give me required output. Everything is perfect now
System.out.printf("%s ", convertedText[i]);
} else {
System.out.printf("%s", convertedText[i]);
i++;
}
}
}
}
}
Current output : VISHNUadgjkxm
Required output: VISHNU VARDHAN
i dont know if converting string to charArray is required but i hope this will do. comment below if you have questions open for revision.
String text = "aVeIwSjjHaNgUkkVarqddlhxn";
//this is the holder of your new processed text.
String newText = "";
//start of counter. it may start in any number depends on requirements.
int x = 0;
//loop while the x is lessthan the length of your string.
while(x < text.length()){
//check if the x + 1 is not equal to the length of your string to avoid StringIndexOutOfBoundsException
if((x+1) != text.length()){
//in this area it will check if the current char is the same on next index
if(text.charAt(x) == text.charAt(x+1)){
// this will concatenate/append the value of char with space
newText += text.charAt(x) +" ";
// this will increase the value of your x by 1 and at the bottom there are also x++ that will add 1 to your x so the total sum of x if (text.charAt(x) == text.charAt(x+1)) are true, will be 2.
x++;
}
}
newText += text.charAt(x);
x++;
}
System.out.println(newText);
output :
aVeIwSj jHaNgUk kVarqd dlhxn
if this is not what you looking for please kindly update your question.
Fixed:
/**
*
* #author Chintu
*/
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUkkVarqdlhxn";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i+1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;
System.out.printf("%s ",convertedText[i]);
}
}
System.out.printf("%s", convertedText[i]);
}
}
}
Fixed
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 0; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i += 2;
System.out.printf(" %s", convertedText[i]);
} else {
i++;
System.out.printf("%s", convertedText[i]);
}
}
}
}
}
output: VISHNU VARDHAN
Related
Problem: Check if the numbers in the string are in increasing order.
Return:
True -> If numbers are in increasing order.
False -> If numbers are not in increasing order.
The String sequence are :
CASE 1 :1234 (Easy) 1 <2<3<4 TRUE
CASE 2 :9101112 (Medium) 9<10<11<12 TRUE
CASE 3 :9991000 (Hard) 999<1000 TRUE
CASE 4 :10203 (Easy) 1<02<03 FALSE
(numbers cannot have 0 separated).
*IMPORTANT : THERE IS NO SPACES IN STRING THAT HAVE NUMBERS"
My Sample Code:
// converting string into array of numbers
String[] str = s.split("");
int[] numbers = new int[str.length];
int i = 0;
for (String a : str) {
numbers[i] = Integer.parseInt(a.trim());
i++;
}
for(int j=0;j<str.length;j++)
System.out.print(numbers[j]+" ");
//to verify whether they differ by 1 or not
int flag=0;
for(int j=0;j<numbers.length-1;j++){
int result=Integer.parseInt(numbers[j]+""+numbers[j+1]) ;
if(numbers[j]>=0 && numbers[j]<=8 && numbers[j+1]==numbers[j]+1){
flag=1;
}
else if(numbers[j]==9){
int res=Integer.parseInt(numbers[j+1]+""+numbers[j+2]) ;
if(res==numbers[j]+1)
flag=1;
}
else if(result>9){
//do something
}
}
This is the code I wrote ,but I cant understand how to perform for anything except one-digit-numbers ( Example one-digit number is 1234 but two-digit numbers are 121314). Can anyone have a solution to this problem?. Please share with me in comments with a sample code.
I'm gonna describe the solution for you, but you have to write the code.
You know that the input string is a sequence of increasing numbers, but you don't know how many digits is in the first number.
This means that you start by assuming it's 1 digit. If that fails, you try 2 digits, then 3, and so forth, until you've tried half the entire input length. You stop at half, because anything longer than half cannot have next number following it.
That if your outer loop, trying with length of first number from 1 and up.
In the loop, you extract the first number using substring(begin, end), and parse that into a number using Integer.parseInt(s). That is the first number of the sequence.
You then start another (inner) loop, incrementing that number by one at a time, formatting the number to text using Integer.toString(i), and check if the next N characters of the input (extracted using substring(begin, end)) matches. If it doesn't match, you exit inner loop, to make outer loop try with next larger initial number.
If all increasing numbers match exactly to the length of the input string, you found a good sequence.
This is code for the pseudo-code suggested by Andreas .Thanks for the help.
for (int a0 = 0; a0 < q; a0++) {
String s = in.next();
boolean flag = true;
for (int i = 1; i < s.length() / 2; i++) {
int first = Integer.parseInt(s.substring(0, i));
int k=1;
for (int j = i; j < s.length(); j++) {
if (Integer.toString(first + (k++)).equals(s.substring(j, j + i)))
flag = true;
else{
flag=false;
break;
}
}
if (flag)
System.out.println("YES");
else
System.out.println("NO");
}
I would suggest the following solution. This code generates all substrings of the input sequence, orders them based on their start index, and then checks whether there exists a path that leads from the start index to the end index on which all numbers that appear are ordered. However, I've noticed a mistake (I guess ?) in your example: 10203 should also evaluate to true because 10<203.
import java.util.*;
import java.util.stream.Collectors;
public class PlayGround {
private static class Entry {
public Entry(int sidx, int eidx, int val) {
this.sidx = sidx;
this.eidx = eidx;
this.val = val;
}
public int sidx = 0;
public int eidx = 0;
public int val = 0;
#Override
public String toString(){
return String.valueOf(this.val);
}
}
public static void main(String[] args) {
assert(check("1234"));
assert(check("9101112"));
assert(check("9991000"));
assert(check("10203"));
}
private static boolean check(String seq) {
TreeMap<Integer,Set<Entry>> em = new TreeMap();
// compute all substrings of seq and put them into tree map
for(int i = 0; i < seq.length(); i++) {
for(int k = 1 ; k <= seq.length()-i; k++) {
String s = seq.substring(i,i+k);
if(s.startsWith("0")){
continue;
}
if(!em.containsKey(i))
em.put(i, new HashSet<>());
Entry e = new Entry(i, i+k, Integer.parseInt(s));
em.get(i).add(e);
}
}
if(em.size() <= 1)
return false;
Map.Entry<Integer,Set<Entry>> first = em.entrySet().iterator().next();
LinkedList<Entry> wlist = new LinkedList<>();
wlist.addAll(first.getValue().stream().filter(e -> e.eidx < seq
.length()).collect(Collectors.toSet()));
while(!wlist.isEmpty()) {
Entry e = wlist.pop();
if(e.eidx == seq.length()) {
return true;
}
int nidx = e.eidx + 1;
if(!em.containsKey(nidx))
continue;
wlist.addAll(em.get(nidx).stream().filter(n -> n.val > e.val).collect
(Collectors.toSet()));
}
return false;
}
}
Supposed the entered string is separated by spaces, then the code below as follows, because there is no way we can tell the difference if the number is entered as a whole number.
boolean increasing = true;
String string = "1 7 3 4"; // CHANGE NUMBERS
String strNumbers[] = string.split(" "); // separate by spaces.
for(int i = 0; i < strNumbers.length - 1; i++) {
// if current number is greater than the next number.
if(Integer.parseInt(strNumbers[i]) > Integer.parseInt(strNumbers[i + 1])) {
increasing = false;
break; // exit loop
}
}
if(increasing) System.out.println("TRUE");
else System.out.println("FALSE");
I have a strings that contain only digits. String itself would look like this "0011112222111000" or "1111111000". I'd like to know how can I get an array of substrings which will consist of strings with only one digit.
For example, if I have "00011111122233322211111111110000000" string, I 'd like it to be in string array(string[]) which contains ["000","111111","222","333","222","1111111111","0000000"].
This is what I've tried
for (int i = (innerHierarchy.length()-1); i >= 1; i--) {
Log.e("Point_1", "innerHierarchy " + innerHierarchy.charAt(i));
c = Character.toChars(48 + max);
Log.e("Point_1", "c " + c[0]);
if (innerHierarchy.charAt(i) < c[0] && innerHierarchy.charAt(i - 1) == c[0]) {
Log.e("Point_1", "Start " + string.charAt(i));
o = i;
} else if (innerHierarchy.charAt(i) == c[0] && innerHierarchy.charAt(i - 1) < c[0]) {
Log.e("Point_1", "End " + string.charAt(i));
o1 = i;
string[j] = string.substring(o1,o);
j=j+1;
}
}
But this code won't work if string looks like this "111111000"
Thank you.
I have "00011111122233322211111111110000000" string, I 'd like it to
be in string array(string[]) which contains
["000","111111","222","333","222","1111111111","0000000"]
One approach I can think of right now (O(n)) (might not be the most efficient but would solve your problem) would be traversing the string of numbers i.e. ("00011111122233322211111111110000000" in your case )
and if char at that position under consideration is not same as char at previous position then making string till that part as one string and continuing.
(approach)
considering str= "00011111122233322211111111110000000"
//starting from position 1 (ie from 2nd char which is '0')
//which is same as prev character ( i.e 1st char which is '0')
// continue in traversal
// now char at pos 2 which is again '0'
// keep traversing
// but then char at position 3 is 1
// so stop here and
//make substring till here-1 as one string
//so "000" came as one string
//continue in same manner.
code
import java.util.*;
public class A {
public static void main(String []args){
String str = "00011111122233322211111111110000000";
str+='-'; //appended '-' to get last 0000000 as well into answer
//otherwise it misses last string which i guess was your problem
String one_element ="";
int start=0;
for(int i=1;i<str.length();i++){
if(str.charAt(i)== str.charAt(i-1) )
{
}
else{
one_element = str.substring(start,i);
start = i;
System.out.println(one_element);//add one_element into ArrayList if required.
}
}
}
}
I have printed each element here as string , if you need an array of all those you can simply use an array_list and keep adding one_element in array_list instead of printing.
I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}
I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.
Here's my code so far.
public class CountLetters {
public static void main( String[] args ) {
String input = JOptionPane.showInputDialog("Write a sentence." );
int amount = 0;
String output = "Amount of letters:\n";
for ( int i = 0; i < input.length(); i++ ) {
char letter = input.charAt(i);
amount++;
output = input;
}
output += "\n" + amount;
JOptionPane.showMessageDialog( null, output,
"Letters", JOptionPane.PLAIN_MESSAGE );
}
}
You don't need 26 switch cases. Just use simple code to count letter:
String input = userInput.toLowerCase();// Make your input toLowerCase.
int[] alphabetArray = new int[26];
for ( int i = 0; i < input.length(); i++ ) {
char ch= input.charAt(i);
int value = (int) ch;
if (value >= 97 && value <= 122){
alphabetArray[ch-'a']++;
}
}
After done count operation, than show your result as:
for (int i = 0; i < alphabetArray.length; i++) {
if(alphabetArray[i]>0){
char ch = (char) (i+97);
System.out.println(ch +" : "+alphabetArray[i]); //Show the result.
}
}
Create an integer array of length 26.
Iterate each character of the string, incrementing the value stored in the array associated with each character.
The index in the array for each character is calculated by x - 'a' for lower case characters and x - 'A' for upper case characters, where x is the particular character.
You can create an Array which first element will represent 'a', second 'b', etc. If you need distinction between lower and upper cases than you can add it at the end. This array will have all values equals 0 at the beginning.
Then you iterate through your sentence and you increment required values on the array.
At the end you print all values that are > 0. Simple?
Let me know if you need more help
No you should not create an array of 26. This will break if the string contains unexpected characters. (ä, ö, ü anyone?)
As I pointed out im my comment use a Map. This will work forr all posible characters out there.
import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException
{
int i,j=0,repeat=0;
String output="",input;
char c=' ';
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter name ");
input=br.readLine();
System.out.println("entered String ->\""+input+"\"");
input=input.toLowerCase();
for(i=0;i<input.length();i++)
{
for(j=0;j<output.length();j++)
{
if(input.charAt(i)==output.charAt(j) || input.charAt(i)==c)
{
repeat=1;
break;
}
}
if(repeat!=1)
{
output=output+input.charAt(i);
}
repeat=0;
}
System.out.println("non-reepeated chars in name ->\""+output+"\"");
int count[]=new int[output.length()];
for(i=0;i<output.length();i++)
{
for(j=0;j<input.length();j++)
{
if(output.charAt(i)==input.charAt(j))
count[i]=count[i]+1;
}
}
for(i=0;i<output.length();i++)
System.out.println(output.charAt(i)+"- "+count[i]);
}
}
How can i get the # of times a single word is in a given sentence.. String.split cannot be used.. I don't really need the code. I just need an idea to get started..
package exam2;
import java.util.Arrays;
public class Problem2 {
/**
* #param args
*/
public static String input, word, a, b, c;
public static int index;
public static void Input() {
System.out.println("Enter Sentence: ");
input = IO.readString();
System.out.println("Enter Word: ");
word = IO.readString();
}
public static void Calc() {
Input();
index = input.indexOf(word);
int[] data = new int[input.length()];
data[0] = index;
while (index >= 0) {
System.out.println("Index : " + index);
for (int i = 1; i < data.length; i++) {
data[i] = index;
}
index = input.indexOf(word, index + word.length());
}
int count = 0;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
if (data[i] == data[j]) {
a = input.substring(data[i], data[i] + word.length());
}
else if (data[i] != data[j]) {
b = input.substring(data[i], data[i] + word.length());
c = input.substring(data[j], data[j] + word.length());
}
}
}
if (a.equalsIgnoreCase(word)) {
count++;
}
System.out.println(count);
}
public static void main(String[] args) {
Calc();
}
}
using a while loop i finding the index of word given by the user in the sentence again given by the user.. I am storing those index in the array. for some reason that is not working.. so i found another way of implementing it. if the index of that word in the array is the equals each other then the word only exits once. I have got this to work.. but if the word exits more than once that is creating the problem..
Get the first letter of the word given by user.Next look at the sentence and find the letter.Then check the second letter of the word and compare it with the next letter in sentence . If its same again continue comparing .If not start again from next letter. Each time you get all the letters of the word and then a space you add 1 to a counter.Think that will work.
Take a look at String.indexOf(String, int). This finds the next position of the parameter String, starting at the parameter int.
Split can't be used? That seems rather odd. I'll bite though, and say simply that we don't have enough information to give a correct answer.
What is a word exactly?
How should symbols/letters be considered?
When is a sentence completed?
Should hyphened words be special?
Do we have 1 sentence and we are testing many words?
Do we have 1 word and many sentence?
What about substring matches (can vs canteen)?
Given what I can guess you should loop through the "sentence" tokenized the input by building "words" until you hit word boundary. Put the found words into a HashMap (keyed on the word) and increment the value for each word as you find it.
You need to call 'input.indexOf(word, fromIndex)' in a loop to find the string. Each time you call this function and it returns something other than -1 increment your count. When it returns -1 or you reach the end of the string stop. fromIndex will start at 0 and will need to be incremented each time you find a string by the length of the string.