My task is to read the strings by input, and then display the strings that have more than 4 vowels in each. I have this code:
import java.util.Scanner;
public class Main {
static boolean vowelChecker(char a) {
a = Character.toLowerCase(a);
return (a=='a' || a=='e' || a=='i' || a=='o' || a=='u' || a=='y');
}
static int counter(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (vowelChecker(str.charAt(i))) {
++count;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
String str = scanner.nextLine();
int b = counter(str);
if (b > 4) {
System.out.println("What do I write here?");
}
}
}
And my question is: how to correctly write the code so that the output would be strings from input that have more than 4 vowels?
import java.util.Scanner;
public class Test {
private static final char[] VOWELS = new char[]{'a', 'e', 'i', 'o', 'u', 'y'};
public static void main(String[] args) {
// Initialize and open a new Scanner
final Scanner scanner = new Scanner(System.in);
// Get the number of lines we want to analyze
System.out.print("Enter the number of elements you want to store: ");
final int n = Integer.parseInt(scanner.nextLine());
// Get all the lines from the user
System.out.println("Enter the elements of the array: ");
final String[] lines = new String[n];
for(int i = 0; i < n; i++) {
lines[i]=scanner.nextLine();
}
// Close the Scanner
scanner.close();
// Check each line, count the number of vowels, and print the line if it has more than 4 vowels.
System.out.println("\nInputs that have more than 4 vowels");
for(int i = 0; i < n; i++) {
if (countVowels(lines[i]) > 4) {
System.out.println(lines[i]);
}
}
}
private static boolean isVowel(char a) {
for (int i = 0; i < VOWELS.length; i++) {
if (Character.toLowerCase(a) == VOWELS[i]) {
return true;
}
}
return false;
}
private static int countVowels(final String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
count++;
}
}
return count;
}
}
Like others have pointed out, you never read from the array.
Read for each of the strings, if the counter() returns a value larger than 4, we want to print it. So, this could do the trick:
for(int i=0; i<n; i++)
{
if (counter(array[i]) > 4)
System.out.println(array[i]);
}
Using nextInt won't absorb the newline character \n, that's why you are inputting 1 string less. There are some workarounds that you can read about here.
So this first part makes sense :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store:
");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
after this part I would just do :
for (String s: array) {
if (Objects.isNull(s))
break;
if (count(s) >= 5) {
System.out.println(s);
}
}
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
class Main {
static long counter(String str) {
return Arrays.stream(str.split(""))
.filter(c -> Arrays.asList("a", "e", "i", "o", "u", "y").contains(c.toLowerCase()))
.count();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n = scanner.nextInt();
scanner.nextLine();
String[] array = new String[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
String str = scanner.nextLine();
if (counter(str) > 4) {
array[i] = str;
}
}
System.out.println(Arrays.toString(Arrays.stream(array).filter(Objects::nonNull).toArray(String[]::new)));
}
}
I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class
Code :
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sa = new String[n];
for(int i=0;i<n;i++){
sa[i] = sc.nextLine();
}
String odd="";
String even="";
for(int i=0;i<n;i++)
{
for(int j=0;j<sa[i].length();j++)
{
if(j%2!=0){
odd = odd+sa[j].charAt(j);
}
else {
even = even+sa[j].charAt(j);
}
}
System.out.println(odd+" "+even);
}
}
}
ISsue : GEtting run time exception while running the code. --> String index out of bound exception
You can try below code. It is because of calling a method like nextInt() before sc.nextLine()
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.
You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array size");
int n = Integer.parseInt(sc.nextLine());
String[] sa = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element "+i);
String val = sc.nextLine();
sa[i]=val;
}
String odd = "";
String even = "";
for (int i = 0; i < n; i++) {
for (int j = 0; j < sa[i].length(); j++) {
if (j % 2 != 0) {
odd = odd + sa[j].charAt(j);
} else {
even = even + sa[j].charAt(j);
}
}
System.out.println(odd + " " + even);
}
}
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();
}
}
}
I want to help me in this program.
Write a program that prompts the user to enter a string and displays the characters at even positions.
package lab6b;
import java.util.Scanner;
public class Lab6b {
public static void main(String[] args) {
Scanner in = new Scanner("Enter a number:");
char s = 0;
for (int i = 0; i < s.charAt(i); i++) {
if (i % 2 == 0) {
continue;
} else if (i % 2 == 1) {
break;
}
}
}
}
You could do like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:");
String enteredString = in.next();
for (int i = 1; i < enteredString.length(); i+=2) {
System.out.println(enteredString.charAt(i));
}
But I think you have to look into things like Scanner, String, loops etc...
The use Scanner class for input you must pass System.inas argument,then use<object>.nextLine()to accept String object then iterate from 1 to s.length()-1 with increment by 2.
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=in.nextLine();
for(int i=1;i<s.length();i+=2)
System.out.print(s.charAt(i));
//I assume the user understands the string begins with 1...s.length()
}