I'm trying to print some elements in array.My array is like,
prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"}
what I'm trying to print is,
int[] float[][] string[][][]
I've been trying various things and it got messy now..
My code is,
String ps="";
int u=0;
for(int y=0;y<prmArray.length;y=u)
{
String br_string="";
if(prmArray[y].equals("[]")){
int f=y+1;
br_string+="[]";
for(int h=f;h<prmArray.length;h++){
u=h;
if(prmArray[h]=="[]"){
br_string+="[]";
}
else{
u=u-1;
break;
}
}
ps+=prmArray[u+1]+br_string+" ";
u=u+2;
}
else{
ps+=prmArray[y]+" ";
u=u+1;
}
}
System.out.println(ps);
please help..
You can use this function:
public static String formatArray(String[] prmArray){
String result = "";
String tempResult = "";
for (String entry: prmArray){
if(entry.equals("[]")){
tempResult += entry;
}else{
tempResult = entry + tempResult;
//flip tempResult
result += tempResult + " ";
tempResult = "";
}
}
return result;
}
Stack implementation:
import java.util.Stack;
public class Stk {
public static void main(String...orange)
{
String [] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};
Stack<String> stack = new Stack<String>();
for (String str : prmArray)
{
if (str.equals("[]"))
stack.push(str);
else
{
while(!stack.isEmpty())
str+=stack.pop();
System.out.print(str + " ");
}
}
}
}
Output:
int[] float[][] string[][][]
If I have well understood what you are trying to do, you don't need nested loops, you can do it in a single pass, putting in your br_string the "[]" you've encountered so far.
When you find something else you build a part of your final result (ps ) and go on ;-)
public static void main(String[] args) {
String[] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};
String ps = "";
String br_string="";
for (int i = 0 ; i< prmArray.length ; i++) {
if(prmArray[i].equals("[]")){
br_string += prmArray[i];
} else {
br_string = prmArray[i] + br_string + " ";
ps += br_string;
br_string = "";
}
}
System.out.println(ps);
}
Related
I saw a code segment as follows:
public class Practice
{
public static void main( String[] args )
{
String i = new String("I love you");
System.out.println(doSomething(i));
}
public static String doSomething( String s )
{
final String BLANK = " ";
String str = "";
String temp;
for ( int i = 0; i < s.length(); i++)
{
temp = s.substring(i, i + 1);
if (!(temp.equals(BLANK)))
{
str += temp;
}
}
return str;
}
}
I am very confused by the code here. I believe that whenever the for loop runs, one of the characters of the String will be extracted out. For example, when i = 0, temp should be "I", and i = 1, " ", i = 2, "l", etc. And when temp = " ", the if statement states that the blank will be adding to the String str. So whenever for-loop is run, the temp will change accordingly and hence cannot store the value unless its value is " ".
The output is Iloveyou.
Here is the problem:
if (!(temp.equals(BLANK)))
{
str += temp;
}
IF temp IS NOT (the ! means NOT) BLANK,
then do: str += temp;
The problem is that it must compare two Strings (example in a text file), and show the differences in it.
Should in the output also be printed out the equals Elements ?
Instead of using for loops, maybe there are different solutions to reach it.
How can it be done ?
Code
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s");
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) {
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) {
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}
A possible solution :
package parsetest;
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s"); // split into single words
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>(); // create ArrayList with more methods to manipulate, avaiable from the api
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) { // adding single elements of array[] to ArrayList
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) { // walking thru the arraylists with remaining elements and printing out results
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}
Here is my code to print string characters reversed in Java without using any API. But it's not working properly. Can anybody help me to correct it?
public static void main(String args[]) {
String input = "I am test";
String result = "";
for (int i = input.length() - 1; i > 0; i--) {
Character c = input.charAt(i);
if (c != ' ') {
result = c + result;
} else {
System.out.println(result + " ");
}
}
}
It is giving output "test amtest", while the output should be "test am I".
Please help me to get exact output without using predefined methods or API's.
There are four problems with your implementation:
You do not go all the way down to zero,
You put an end of line after each printout in the loop,
You do not print the "tail" result after the loop is over, and
You do not clear out result after printing it in the loop.
Fixing these issues will give you proper output (demo).
try
public static void main(String args[]) {
String input = "I am test";
String result = "";
int start=input.length()-1;
for (int i = input.length()-1; i >=0; i--) {
Character c = input.charAt(i);
if (c == ' ') {
for(int j=i+1;j<=start;j++)
result +=input.charAt(j);
result+=" ";
start=i-1;
}
else if (i==0)
{
for(int j=0;j<=start;j++)
result +=input.charAt(j);
}
}
System.out.println(result);
}//It is giving output as test amtest
//output should be : test am I
public static void main(String args[]) {
String input = "I am test";
String result = "";
String[] frags = input.split(" ");
for (int i = frags.length - 1; i >= 0; i--) {
System.out.print(frags[i] + " ");
}
System.out.println();
}
You can try recursion as well -
public static void main(String args[]) {
String input = "I am test";
List<String> listOfString = Arrays.asList(input.split(" "));
System.out.println(reverseString(listOfString));
}
private static String reverseString(List<String> input) {
int n = input.size();
String result = "";
if(input.isEmpty()){
return result;
}
if(n>1){
/*adding last element with space and changes the size of list as well
test + " " + [am, I]
test + " " + am + " " + [I]*/
result = input.get(n-1) + " " + reverseString(input.subList(0, n-1));
}else{
result = input.get(n-1);
}
return result;
}
hope it helps.
public static void main(String args[]){
String input = "I am test";
String result="";
for(int i=input.length()-1;i>=0;i--){
result=result+input.charAt(i);
}
System.out.println(result);
}
i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.
Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
"This is an interview question"
The output must be:
"question interview an is this"
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)
Just being different: a recursive solution. Doesn't add any extra spaces.
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
I will also improve on the split solution by using \b instead (it's so obvious!).
String[] parts = "Word boundary is better than space".split("\\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.
(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).
Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
a every boring bit of java:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
in groovy it's a little bit more readable:
"this is an interview question"
.split("\\s")
.reverse()
.join(' ')
I also give it a try: Here's a version using a stack and a scanner:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
I don't think you should use any library..
1) Reverse whole string
2) Reverse each word.
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
please try below solution, this is working for me.
public class reverseline {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="This is interview question";
String words[]=str.split(" ");
for(int i=words.length-1;i>=0;i--){
System.out.print(words[i]+" ");
}
}
}
Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());
Shortest Answer
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
List<String> reverseWord = Arrays.asList(words);
Collections.reverse(reverseWord);
Iterator itr = reverseWord.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
OR
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
for (int i = words.length-1 ; i >= 0; i--) {
System.out.print(words[i] +" ");
}
}
}