Question
Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line.
Assume input starts at index position 0(which is considered even)
Input
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines contain a String, S.
Output
For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
The Code I Wrote
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for(int i=0 ; i<T ; i++)
{
String myString = scan.nextLine();
int evn = 0,
odd = 0,
len = myString.length();
char strE[] = new char[50],
strO[] = new char[50];
for(int j=0 ; j<len ; j++)
{
if(j%2 == 0)
{
strE[evn] = myString.charAt(j);
evn++;
}
if(j%2 == 1)
{
strO[odd] = myString.charAt(j);
odd++;
}
}
System.out.print(strE);
System.out.print(" ");
System.out.println(strO);
}
}
My Output
Hce akr
Rn ak
The Problem
As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.
Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.
Could anyone please tell me where I am making a mistake?
Further Modifications
I then decided to change the last 3 lines of print statements into one statement as follows:
System.out.println(strE + " " + strO);
However, this time the program did not produce the desired output and rather printed some garbage values as follows:
[C#5c3f3b9b [C#3b626c6d
[C#3abc8690 [C#2f267610
My Doubts
1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?
2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?
Here is a link to the HackerRank problem for more info:
hackerrank.com/challenges/30-review-loop
All help and guidance is greatly appreciated and thanks a lot in advance!
Try to submit this:
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for (int i = 0; i < T; i++) {
String myString = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even + " " + odd);
}
i get the right output and it should meet all the requirements. i think your code fails because its not a real string you print in the end and you have empty spots in your arrays
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the no.of test-cases:");
int t = scanner.nextInt();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String(s)");
for (int i = 0; i < t; i++) {
String myString = br.readLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even);
System.out.println(odd);
}
scanner.close();
int T = scan.nextInt();
This reads quantity of test cases, which we're going to process.
String string[] = new String[T];
for(int i = 0; i<T; i++){
string[i] = scan.next();
}
Next we're creating an array named "string" (BTW, this a bad name for variables/objects) which has size T and in the for loop reading test cases from the input T times and saving them in the array.
for(int temp = 0; temp<T; temp++){
Now, for each of test cases we do the following...
for(int j = 0; j<string[temp].length(); j = j+2)
{
System.out.print(string[temp].charAt(j));
}
We create a local variable j, which is visible only in this for loop. j holds index of the string (=string[temp]), which we're processing. So, we're printing a character on position j (by using standard method "charAt" of String class, which returns character of given index of the string) and then increasing it by 2. So, this code will print every even character. For string "example", it will print "eape" (j=0, j=2, j=4, j=6).
System.out.print(" ");
Separating sequences with a space.
for(int j = 1; j<string[temp].length(); j = j+2){
System.out.print(string[temp].charAt(j));
}
System.out.println();
We're doing the same (creating index j, running though all characters of the string), but starting from "1", so it will print all odd characters of the string. For string "example", it will give you "xml" (j=1, j=3, j=5). and After this, it will end the string. I hope, it will help you to understand. :)
I can solve your the second question:
---> System.out.print(strE);-->At the bottom, the method is called( public void print(char s[]));
-->System.out.println(strE + " " + strO);-->At the bottom, the method is called (public void println(String x) )
For your first answer I am unable to answer you as I have no idea about how the compiler works, but I can answer your second question.
The reason why System.out.print(strE); System.out.print(" "); System.out.println(strO); works is because System.out.print(char[]) and System.out.println(char[]) automatically turn the char arrays into a readable string before printing it.
However, in the second case System.out.println(strE + " " + strO);, what you are doing is directly turning the char array into strings, which just prints the class and the hash code of the array object because the toString() method is not overriden in the array class. What you want to do is System.out.println(new String(strE) + " " + new String(strO));. It will give you the result you want.
import java.io.*;
import java.util.*;
public class Solution {
private static void f(String s) {
// TODO Auto-generated method stub
char c[]=s.toCharArray();
int i,j;
for (i = 0; i <c.length;i++){
System.out.print(c[i]);
i+=1;
}
System.out.print(" ");
for (j = 1; j<c.length;j++){
System.out.print(c[j]);
j+=1;
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int s=sc.nextInt();
while(hasNext()){
//for loop for multiple strings as per the input
for(int m=0;m<= s;m++){
String s1=sc.next();
f(s1);
System.out.println();
}
}
}
}
I've solved this question in 2 ways & both are producing correct output.
Have a look & let me know if you've any problem.
Instead of using char array, you can use String
//char[] even = new char[10000];
String even = "";
Let's look at the code
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
//char[] even = new char[10000];
//char[] odd = new char[10000];
String even = "";
String odd = "";
for(char ch : array){
if(count%2 == 0){
even = even + ch;
}else{
odd = odd + ch;
}
count++;
}
count = 0;
System.out.println(even + " " + odd);
}
Output:
hacker
hce akr
No need of extra char[] or String to store even & odd position characters, we can directly print them using appropriate condition.
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
for(char ch : array){
if(count%2 == 0){
System.out.print(ch);
}
count++;
}
count = 0;
System.out.print(" ");
for(char ch : array){
if(count%2 != 0){
System.out.print(ch);
}
count++;
}
count = 0;
}
Output:
hacker
hce akr
Try this:
public static void main(String[] args) {
System.out.println("Enter string to check:");
Scanner scan = new Scanner(System.in);
String T = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < T.length(); j++) {
if (j % 2 == 0) { //check the position of the alphabet by dividing it by 0
even += T.charAt(j);
} else {
odd += T.charAt(j);
}
}
System.out.println(even + " " + odd);
scan.close();
}
** JavaScript version **
function processData(input) {
for (let i = 1; i < input.length; i++) {
printOutput(input[i]);
}
}
function printOutput(input) {
var result = [];
input.length % 2 == 0 ? result[input.length / 2] = ' ': result[Math.ceil(input.length / 2)] = ' ';
for (let i = 0; i < input.length; i++) {
if (i % 2 == 0) {
result[i / 2] = input[i];
}
else {
result[Math.ceil(input.length / 2) + Math.ceil(i / 2)] = input[i];
}
}
console.log(result.join(''));
}
process.stdin.on("end", function () {
processData(_input.split('\n'));
});
import java.io. * ;
import java.util. * ;
public class Solution {
String myString;
public Solution(String myString) {
this.myString = myString;
int len = myString.length();
for (int j = 0; j < len; j++) {
if (j % 2 == 0) {
System.out.print(myString.charAt(j));
}
}
System.out.print(" ");
for (int j = 0; j < len; j++) {
if (j % 2 == 1) {
System.out.print(myString.charAt(j));
}
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System. in );
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
String word = sc.next();
Solution sol = new Solution(word);
System.out.println();
}
sc.close();
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int T;
T = s.nextInt();
String[] str = new String[T];
int i;
for(i=0;i<T;i++) {
str[i] = s.next();
}
for(i=0;i<T;i++) {
char[] even = new char[5000];
char[] odd = new char[5000];
int ev =0,od=0;
for(int j= 0;j< str[i].length();j++) {
if(j%2== 0) {
even[ev] = str[i].charAt(j);
ev++;
}else {
odd[od] = str[i].charAt(j);
od++;
}
}
String strEven = new String(even);
String strOdd = new String(odd);
System.out.print(strEven.trim());
System.out.print(" ");
System.out.println(strOdd.trim());
}
s.close();
}
}
I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int n= scan.nextInt();
for(int i=0;i<n;i++){
String s= scan.next();
int len= s.length();
StringBuffer str_e= new StringBuffer();
StringBuffer str_o= new StringBuffer();
for(int j=0;j<len;j++){
if(j%2==0)
str_e= str_e.append(s.charAt(j));
if(j%2==1)
str_o= str_o.append(s.charAt(j));
}
System.out.println(str_e+" "+str_o);
}
}
}
Try this:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner pp=new Scanner(System.in);
int n=pp.nextInt();
for(int i=0; i<n; i++)
{
String ip=pp.next();
String re1="",
re2="";
for(int j=0; j<ip.length(); j++)
{
if(j%2 == 0)
{
re1+= ip.charAt(j);
}
if(j%2 == 1)
{
re2+= ip.charAt(j);
}
}
System.out.print(re1+" "+re2);
System.out.println("");
}
}
}
public class PrintCharacters{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int noOfTestCases = sc.nextInt();
sc.nextLine();
String []inputStrings= new String[noOfTestCases];
for(int i=0;i<noOfTestCases;i++) {
inputStrings[i]=sc.nextLine();
}
for(String str: inputStrings) {
String even ="";
String odd ="";
for(int i=0;i<str.length();i++) {
if(i%2==0) {
even+=str.charAt(i);
}else {
odd+=str.charAt(i);
}
}
System.out.println(even+" "+odd);
}
sc.close();
}
}
Input:
2
Hacker
Rank
Output:
Hce akr
Rn ak
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
while(n>0) {
String str=scan.next();
for(int i=0;i<str.length();i++) {
if(i%2==0) {
System.out.print(str.charAt(i));
}
}
System.out.print(" ");
for(int i=0;i<str.length();i++) {
if(i%2==1) {
System.out.print(str.charAt(i));
}
}
n--;
System.out.println();
}
}
}
So i decided to print all palindrome words in a string. I didnt use arrays or the method to find palindrome of only 3-character-words.Here is my code,the problem being,it prints out nothing
import java.util.Scanner;
class Pa{
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
String s=sc.nextLine();
char b;
int i,a;
String st="";/to extract a word
s=s+" ";
String t="";/to extract the reverse of the word
a=s.length();
for(i=0;i<a;i++){
b=s.charAt(i);
if(b!=' '){
st=st+b;/word
t=b+st;/reversed word
} else {
if(st.equals(t)){
System.out.println(st);
}
st="";
t="";
}
}
}
}
I cannot figure out what's wrong and would not appreciate the split or 3-word palindrome finder options or the normal even-or-odd only palindrome finding options.
To check whether a String is a Palindrom a single loop is sufficient
public static boolean isPalindrom(String word) {
word = word.toLowerCase();
for (int i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - (i + 1))) {
return false;
}
}
return true;
}
Then you can split your input string at every whitespace like input.split("\\s") and check for every word if it's a palindrom
The simplest way to check palindrome:
private static boolean isPalindrom(String s) {
return s.equals(new StringBuilder(s).reverse().toString());
}
Your problem is below. Instead of appending b to the reversed string, you're appending it to the normal string.
b=s.charAt(i);
if(b!=' '){
st=st+b;
t=b+st; // This should be t=b+t
} else {
//input-mom gives me a pen(reverse-mom sevig em a nep)(checking each word by reverse)//
//output-palindrome//
//input-he is a boy//
//output-not a palindrome//
import java.util.*;
class main2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String str=sc.nextLine(); //he is a boy//
int ctr=0;
String temp="",temp1="",x="",y="";
int i,j;
String str1[]=str.split(" ");//[he,is,a,boy]//
for(i=0;i<str1.length;i++)//length=4//
{
temp=str1[i];//reverse each word//
for(j=temp.length()-1;j>=0;j--)
{
x=x+temp.charAt(j);
}
x=x+" ";
}
System.out.println(x);
for(int k=0;k<str1.length;k++)
{
temp1=str1[k]; //he//
for(int l=temp1.length()-1;l>=0;l--)
{
y=y+temp1.charAt(l);//eh//
}
if(y.equalsIgnoreCase(temp1))//he==eh?//
{
ctr++;
System.out.println(y);//for printing the word//
}
}
if(ctr==0)
System.out.println("Not a palindrome");
else
System.out.println("Palindrome");
}
}
import java.util.*;
class palindrome {
String reverse(String str)
{
String tmp="";
int l=str.length()-1;
for(int i=l,n=0;i>=n;i--)
{
tmp=tmp+str.charAt(i);
}
return tmp;
}
}
class palindrome_word{
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
palindrome ob=new palindrome ();
System.out.println("enter a sentance");
String s=sc.nextLine();
char b;
int i,a;
String st="";//to extract a word
s=s+" ";
String t="";//to extract the reverse of the word
a=s.length();
System.out.println("palindrome words");
for(i=0;i<a;i++){
b=s.charAt(i);
if(b!=' '){
st=st+b;//word
// t=b+st;reversed word
} else {
t=ob.reverse(st);
if(st.equalsIgnoreCase(t)){
System.out.println(st);
}
st="";
t="";
}
}
sc.close();
}
}
I have written a program which takes a String as user input and displays the count of letters, digits and white-spaces. I wrote the code using the Tokenizer-class, and it counts the letters and digits, but it leaves out the white-spaces. Any ideas?
import java.util.Scanner;
public class line {
public static void main(String[] args) {
System.out.println("Enter anything you want.");
String text;
int let = 0;
int dig = 0;
int space= 0;
Scanner sc = new Scanner(System.in);
text = sc.next();
char[]arr=text.toCharArray();
for(int i=0;i<text.length();i++) {
if (Character.isDigit(arr[i])) {
dig++;
} else if (Character.isLetter(arr[i])) {
let++;
} else if (Character.isWhitespace(arr[i])) {
space++;
}
}
System.out.println("Number of Letters : "+let);
System.out.println("Number of Digits : "+dig);
System.out.println("Number of Whitespaces : "+space);
}
}
Scanner by default breaks the input into tokens, using whitespace as the delimiter!
Simply put, it gobbles up all the whitespace!
You can change the delimiter to something else using sc.useDelimiter(/*ToDo - suitable character here - a semicolon perhaps*/).
You have got problem in
sc.next();
except it, use
sc.nextLine();
it should work.
Instead of text = sc.next(); use text = sc.nextLine();
Try using
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Line {
public static void main(String[] args) throws Exception {
String s;
System.out.println("Enter anything you want.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
int length = s.length();
int letters = 0;
int numbers = 0;
int spaces = 0;
for (int i = 0; i < length; i++) {
char ch;
ch = s.charAt(i);
if (Character.isLetter(ch)) {
letters++;
} else {
if (Character.isDigit(ch)) {
numbers++;
} else {
if (Character.isWhitespace(ch)) {
spaces++;
} else
continue;
}
}
}
System.out.println("Number of letters::" + letters);
System.out.println("Number of digits::" + numbers);
System.out.println("Number of white spaces:::" + spaces);
}
}
I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}
How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}