Why is indexOf not working into counting were a string is - java

I am pretty sure indexOf is suppose to print out the number the letter is located! And in my code if it is there is should add to result to see how many "x" are in message! Although it dosen't work it print out 7 meaning it completely ignores my if statement!
public class Test1
{
public static void main(String[] args)
{
String message = "xyxxzax";
int result = 0;
int y = message.length();
for(int x = 0 ; y > x; x++){
String v = message.substring(x,x+1);
if (message.indexOf("x") > -1){
result++;
}
}
System.out.println(result);
}
}

That is because you never change the string message! And I suppose you that this is not how indexOf works. So:
public class Test1
{
public static void main(String[] args)
{
String message = "xyxxzax";
int result = 0;
int y = message.length();
for(int x = 0 ; y > x; x++){
String v = message.substring(x,x+1);
if (v.equals("x")){
result++;
}
}
System.out.println(result);
}
}

Related

String index out of range error - how do I print this string vertically in java?

I'm trying to print a statement vertically, and then backward vertically with two classes so I can practice multiple skills. However, frustratingly, I cannot get my program to work and keep getting a "string index out of range error". I'm not sure if I'm miscalling my functions because I am new to Java.
class Main {
public static void main(String[] args) {
MyString.verPrint("treasure");
MyString.backPrint("treasure");
}
}
public class MyString {
public static String verPrint(String x){
int i = x.length();
while(0 < i){
x = x.charAt(i) + "\n";
i++;
}
return(x);
}
public static String backPrint(String x){
int i = x.length() - 1;
while(i >= 0){
i--;
x = x.charAt(i) + "\n";
}
return(x);
}
}
The problem with your solution is you are updating the input string in the first iteration by assigning a character and a new line to it. Hence, it doesn't work for the latter iterations. I've made some changes in your snippet. You may follow it -
public class Main {
public static void main(String[] args) {
System.out.println(MyString.verPrint("treasure"));
System.out.println(MyString.backPrint("treasure"));
}
}
class MyString {
String x;
public static String verPrint(String x){
int i = x.length();
String y = "";
int j = 0;
while(j < i){
y += x.charAt(j) + "\n";
j++;
}
return(y);
}
public static String backPrint(String x){
int i = x.length() - 1;
String y = "";
while(i >= 0){
y += x.charAt(i) + "\n";
i--;
}
return(y);
}
}
String s="HELLO";
char[] y=s.toCharArray();
for (char x : y) {
System.out.println(x);
}
OUTPUT
H
E
L
L
O
String S="Hello";
S=new StringBuffer(S).reverse().toString();
System.out.println(S);
char[] y=S.toCharArray();
for (char x : y) {
System.out.println(x);
}
You know output
your conditions have problem, while checking for the length and index of x string parameter:
public class Main {
public static void main(String[] args) {
System.out.println(verPrint("treasure"));
System.out.println("-----------");
System.out.println(backPrint("treasure"));
}
public static String verPrint(String x) {
int i = 0;
String result = "";
while (i < x.length()) {
result += x.charAt(i++) + "\n";
}
return result;
}
public static String backPrint(String x) {
int i = x.length() - 1;
String result = "";
while (i >= 0) {
result += x.charAt(i--) + "\n";
}
return result;
}
}

How to run for loop in java?

I would like to know why this code do not run. Is there something missing?
Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".
public class Drumkit {
int countXX(String str){
String a = "abcxxx";
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (a.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
}
You are passing str and using its length() in your function. But, in the loop you're using a (local string variable) which seems like a logical mistake.
You need to pass the input string when your call this function and use str (the function argument) to count the matches.
Here's a functional example:
class Test
{
static int countXX( final String str ) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
public static void main (String[] args)
{
final String s = "abcxxx";
final int count = countXX( s );
System.out.println( count );
}
}
Here's the live example: https://ideone.com/Lm6Ir4
Your problem is unclear. however, you can try this code
public static void main(String[] args) {
final int count = countXX("abcxx efjxx xyzxx xx xxxx xx","xx");
System.out.println(count);
}
static int countXX(final String text, final String occurrenceOf){
int count = 0;
int fromIndex=0;
for (int i = 0; i < text.length() - 1; i++) {
int index = text.indexOf(occurrenceOf,fromIndex);
if(index >-1) {
count++;
fromIndex=index+1;
}
}
return count;
}

Java permutation of String array

I am trying to find all possible options of combining a string array with two elements. Let's say, the array has two elements {"we","are"}. The output should be:"we" "are" "we are" "are we"
I could manage, with some search, to put together this code:
public class Main {
public static void main(String[] args) {
String[] strings = {"we", "are"};
final int maxbit = 1 << strings.length;
for (int p = 0; p < maxbit; p++) {
String finalString = "";
for (int i = 0; i < strings.length; i++) {
if ((1 << i & p) > 0) {
finalString += strings[i] + " ";
}
}
System.out.println(finalString);
}
}
My problem is, that I am missing one solution, the output is following: "we" "are" "we are".
So I am missing the "are we" option, would I need to use recursion to solve this problem or can this code be modified to show the remaining option?
UPDATE: solution found with the help of answers
public static void main(String[] args) {
String[] test = { "are", "we"};
language(test.length, test, "");
}
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
if (currentWord.equals(syllables[i])){
language(n - 1, syllables, "" + syllables[i]);
}else{
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
}
Another example
import java.util.Arrays;
public class HelloWorld{
public static void main(String[] args) {
String[] strings = {"we", "are"};
String str = Arrays.toString(strings);
System.out.println("Java String array to String = "+str.replace(",","").replace("[","").replace("]",""));
}
}
I looked over it for a while, and found 2 ways to make it based on your code:
this will print out every permutation once, and DOESN'T have to include all the words:
public static void recPerm(String... input) {
recHelper(input, input.length, "");
}
private static void recHelper(String[] input, int length, String currentWord) {
if (currentWord != "")
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
recHelper(input, length - 1, currentWord + input[i]);
}
}
this will print out every permutation once, and DOES have to include all the words:
public static void maxRecPerm(String... input) {
maxRecHelper(input, input.length, "");
}
private static void maxRecHelper(String[] input, int length, String currentWord) {
if (length == 0)
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
maxRecHelper(input, length - 1, currentWord + input[i]);
}
}

Alternate display of 2 strings in Java

I have a java program where the following is what I wanted to achieve:
first input: ABC
second input: xyz
output: AxByCz
and my Java program is as follows:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
however I encounter the following runtime error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
What mistake is in my Java program?
If both arrays have same length for loop should continue while i < anyArray.length.
Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.
So your displayStringAlternately method can look like
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).
As you commented, If both arrays length is same, you can simply do
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
Then
for(int i = 0; i < firstC.length; i++) {
System.out.print(firstC[i]);
System.out.print(secondC[i]);
}
Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.
Try the below working code with high performance
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < firstC.length; i++) {
builder.append(firstC[i]);
builder.append(secondC[i]);
}
System.out.println(builder.toString());
}
public class concad {
public void main(String[] args) {
String s1 = "RAMESH";
String s2 = "SURESH";
int i;
int j;
for (i = 0; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
for (j = i; j <= i; j++) {
if (j == i) {
System.out.print(s2.charAt(j));
}
}
}
}
}
I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.
public class AlternatePosition {
public static void main(String[] arguments) {
String abc = "abcd";
String def = "efgh";
displayStringAlternately(abc, def);
}
public static void displayStringAlternately(String firstString, String secondString) {
for (int i = 0; i < firstString.length(); i++) {
for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
if (counter % 2 == 0) {
System.out.print(secondString.charAt(i));
break;
} else {
System.out.print(firstString.charAt(i));
}
}
}
}
}

find the value of variable given in a string

Given a equation :
433+4H8= 871
H can be anyside of equation. Find the value of H and replace it in given equation.
The output should be :
433+438=871
I have tried the following code but conversion of string to int does not work...
import java.util.Scanner;
import java.io.*;
class hole
{
public static void main(String[] args)
{
Scanner reader= new Scanner(System.in);
int[] nums= new int[3];
String str= reader.nextLine();
String str_1= str.replaceAll("=","+");
String[] split= str_1.split("[+]");
for (int k=0; k<split.length; k++)
{
String ex= split[k];
nums[k]= Integer.parseInt(ex);
}
}
}
4H8 isn't an integer, so parseInt won't work on it.
It seems like you still have a bit of a way to go on this, so I won't spoil your fun by giving you the code, just some ideas.
Assuming the equation is always X + Y = Z, which X, Y and Z being some integers, one of which can contain an H...
You need to have a couple of cases:
If the H is in X, you can get X by subtracting Y from Z.
If the H is in Y, you can get Y by subtracting X from Z.
If the H is in Z, you can get Z by adding X and Y.
But this still doesn't give you H. For this, you can simply find the position of the H in the string we have and extract the digit at that position in the number calculated above.
So before calling parseInt, you should look for the H and simply store the string instead if you find it.
parseInt also doesn't like spaces, so you should remove those in some way or another.
If equations aren't always in the form X + Y = Z (i.e. you can also have subtraction, multiplication, division and/or multiple terms), it gets a bit more complicated.
Why would you not just subtract the final answer minus the first number and build the third number. Splitting the string is redundant as you can just use simple math to solve for x.
871-433 = 438
h=3
public static void main(String[] args)
{
int a = 433;
int b = 871;
int c = b - a;
String s = "4H8";
char x;
int location = 0;
for(int i = 0; i < s.length(); i++)
{
char d = s.charAt(i);
if(d.isDigit()){
}
else{
location = i;
x = d;
}
}
String solve = c.toString();
System.out.println(x + "=" + solve.charAt(location) );
}
Try this (comments are self explanatory):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
int varIndex = 0;
int result = 0;
String str = reader.nextLine();
//remove spaces and split into 3 parts based on symbols
String[] components = str.replaceAll(" ", "").split("\\+|=");
for (int i = 0; i < components.length; i++) {
try {
nums[i] = Integer.parseInt(components[i]);
} catch (Exception e) {
varIndex = i; //this component contains "H"
}
}
//Calculate the value of the number which has "H"
switch (varIndex) {
case 0:
result = nums[2] - nums[1]; break;
case 1:
result = nums[2] - nums[0]; break;
case 2:
result = nums[0] + nums[1]; break;
}
nums[varIndex] = result;
//Print the output
System.out.println(nums[0] + " + " + nums[1] + " = " + nums[2]);
System.out.println("H = " + (String.valueOf(result)).charAt(components[varIndex].indexOf('H')));
}
Try below program , This works only for input a+b=c format
Below program is giving correct output
import java.util.Scanner;
public class Hole {
public static void main(String args[])
{
int hLocation = 0;
int result;
char hValue;
Scanner in=new Scanner(System.in);
String str=in.nextLine().replaceAll(" ", "");
String[] split= str.split("[+=]");
for(int i=0;i<split.length;i++){
if(split[i].contains("H")){
hLocation=i;
}
}
if(hLocation==0){
result=Integer.parseInt(split[2])-Integer.parseInt(split[1]);
}else if(hLocation==1){
result=Integer.parseInt(split[2])-Integer.parseInt(split[0]);
}
else{
result=Integer.parseInt(split[0])+Integer.parseInt(split[1]);
}
hValue= String.valueOf(result).charAt(1);
str=str.replace('H', hValue);
System.out.println(str);
}
}
Try this:
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
boolean[] isNum = new boolean[3];
String str = reader.nextLine();
// String str_1= str.replaceAll("=","+");
String[] split = str.split("[+=]");
int i = 0;
for (int k = 0; k < split.length; k++) {
try {
String s = split[k];
isNum[k] = true;
nums[i] = Integer.parseInt(s);i++;
} catch (NumberFormatException e) {
// TODO: handle exception
isNum[k] = false;
}
}
int tot ;
if(str.indexOf("H")>str.indexOf("=")){
tot = nums[1] + nums[0];
}else{
tot = nums[1] - nums[0];
}
for (int k = 0; k < split.length; k++) {
if(!isNum[k]){
int indx = split[k].indexOf("H");
String h = Integer.toString(tot).charAt(indx)+"";
h = str.replace("H",h);
System.out.println("New expression :"+h);
}
}
}

Categories