Characters Array - java

I am trying to print every second letter in the string but for some reason I only print the first second letter correctly but after that it keeps printing in a weird order. Here is my code:
out.print("Please enter a word: ");
String word = in.nextLine();
char[] c = word.toCharArray();
int x = 0;
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
x++;
}

You should change this:
if (c[x] % 2 != 0) {
to
if (x % 2 != 0) {
This compares the index you are working with instead of comparing the character. x is the position of the character. c[x] is the character. You can read c[x] as "the value at position x in array c".

Why are you attempting to determine if the character (c[x]) is odd? You should be testing the index itself.
if (x % 2 != 0) {

You are calculating the character modulo 2 instead of the index modulo 2
By the way:
String word …
for(int ix=1; ix<word.length(); ix+=2)
out.print(word.charAt(ix) + " ");
makes it far simpler.

Problem area: You are checking value instead of index
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
Convert it to: Checking index instead of value
while (x < c.length) {
if (x % 2 != 0) {
out.print(word.charAt(x) + " ");
}

Related

What is a good way to output why an object won't go through all of the "if" statements?

I am making a program that checks to see if an elements positive and negative charges are able to combine to make 0. A thing i want to do is output the reasons why the two elements are not able to combine. But it is more difficult than i expected. for example if sodium were trying to combine with copernicium, it would output this:
Sodium doesn't combine with Copernicium:
Both valence charges have same polarity.
One or more elements is man-made.
but i can not think of a way to implement this into my code.
here is my code:
public void combine(Element element){
if ((element.getValence() > 0 && valence < 0) || (element.getValence() < 0 && valence > 0)) { //one element needs a positive valence, and one needs a negative valence
if (valence != 0 && element.getValence() != 0) { //checks to see if valence is not equal to 0
if (natural == true && element.isNatural() == true) { //checks to see if both elements are natural
for (int x = 1; x <= 4; x++) {//bruteforce the atoms to see if they both add up to 0.
for (int y = 1; y <= 4; y++) {
if ((valence * x) + (element.getValence() * y) == 0) {
System.out.println(name + " combines with " + element.getName() + " to form " + symbol + "" + x + "" + element.getSymbol() + "" + y);
}
}
}
}
}
}
}
Thanks for any help!
The way to do this is to add else clauses for each if that return an appropriate message.
if ((element.getValence() > 0 && valence < 0) || (element.getValence() < 0 && valence > 0)) { //one element needs a positive valence, and one needs a negative valence
{
// the inner tests
}
else
{
System.out.println("The elements are both positive or both negative");
}
}
This should get you started in the right direction.

How to check for every second and fifth position in a String?

This code prints yup to every second char (1,3,5,7,9..). Now I'm having a problem because I need also print a word for example " yap " to every fifth char (4,9,14,19...). So every tenth is yup yap etc... Appreciate if you have any hints or solution. Thank you for help!
for(int i = 0; i < word.length(); i++){
if( i % 2 != 0 && i > 0) {
System.out.print(word.charAt(i) + " yup");
System.out.println();
}
else{
System.out.println(word.charAt(i));
}
}
Just add else if statements like
else if (i + 1 % 5 == 0) {
// for every fifth
} else if (i + % 10 == 0) {
// for every tenth
}
and remove an unnecessary check i > 0 in the if statement.

Too many Exception out of bounds - JAVA

Code is supposed to do this: Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
The problem: Ran across Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 11 (line number:10)
public int countCode(String str){
int a = 0; // counter goes thru string
int b = str.length()-1;
int counter = 0; //counts code;
if(str.length() < 4) return 0;
else{
while (a <=b){
if(str.charAt(a) == 'c'){
if(str.charAt(a+1) == 'o'){
if(str.charAt(a+3) == 'e'){
counter++;
a= a+3;
} // checks e
else a++;
} // checks o
else a++;
} // checks c
else a++;
}
return counter;
}
}
Here's what I tried to evaluate to get said exception:
countCode("xxcozeyycop") --> EXPECTED RESULT 1
countCode("cozcop") --> EXPECTED RESULT
Your loop goes from 0 to the length of the string (excluded). But inside the loop, you're doing
str.charAt(a+3)
Obviously, if a is length - 1, a + 3 is length + 2, and you're thus trying to access an element outside the bounds of the string.
Side note: you would understand your own code better if you indented it correctly.
Instead of
while (a <=b){
use
while (a <= b - 3){
Reason: Your end sign in the while is the condition that the start of the String "code" is inside the String. However, if a = b - 2, then a + 3 = b + 1 = (str.length() - 1 + 1) = str.length() which is just outside the String.
public int countCode(String str) {
int count = 0;
for(int i = 0; i < str.length()-3; i++)
if(str.substring(i, i+2).equals("co") && str.charAt(i+3) == 'e')
count++;
return count;
}

How to count in Java the trailing zeros from an Integer? (Ex: 234000 => 3 zeros)

The title is pretty much self explanatory. :)
1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5
If it fits into an int/long, just check if the number modulo 10 is 0 and keep a counter:
long x = ...
if (x == 0) {
return 0;
}
int counter = 0;
while (x % 10 == 0) {
counter++;
x /= 10;
}
If it's too big to fit in long, store it in a String and count zeroes from the last char:
String s = ...
int counter = 0;
while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
counter++;
}
Integer class has an inbuilt function to count the trailing zeros.
javadocs
int trailingZeroes = Integer.numberOfTrailingZeros(int i);
Three lines:
int zeroes = 0
while(num%10 == 0 && num != 0) {
zeroes++;
num /= 10;
}
This uses the modulus operator. As long as we can divide by ten without remainder, increment the counter.
Here is another solution using Java 8 Streams:
int trailingZeros = String.valueOf(number).chars()
.reduce(0, (count, ch) -> (ch == '0') ? count + 1 : 0);
This transforms the number to an IntStream. This stream is then reduced using a lambda which resets a counter each time a non-zero char comes up.
You could always just use a regular expression:
Pattern pattern = Pattern.compile("(0+)$");
Matcher matcher = pattern.matcher(String.valueOf(123140000));
Integer trailingZeroes = 0;
if (matcher.find()) {
trailingZeroes = matcher.group(1).length();
}
System.out.println(trailingZeroes);
you can turn the int to a String and iterate in reverse, counting the zeros until you find a char that is not zero:
int countZeros(int x){
String a = Integer.toString(x);
int numOfZeros = 0;
for(int i = a.length() - 1; i >= 0; i--)
if (a.charAt(i) != '0') break;
else numOfZeros ++;
return numOfZeros;
}
Testing with :
System.out.println(countZeros(25000)); will print 3
System.out.println(countZeros(25)); will print 0
Hope this helps.
Not tried this code but this should work.
int counterForZeros=0;
for(long i=10;true;)
{
if(num%i==0)
{
counterForZeros++;
i*=10;
}
else
{
break;
}
}
System.out.println("Number of zeros in "+num+" is "+counterForZeros);
Well, if this is a contest to see who can do it in the fewest lines:
trailingZeroes = String.valueOf(num).length() - String.valueOf(num).replaceAll("0*$","").length();

Remove the comma after the last number in a loop [duplicate]

This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 5 years ago.
this is my code
System.out.println("Enter any integer number ");
int number = scan.nextInt();
while (number > 0) { System.out.print( number % 10 + ",");number = number / 10;}
To clarify if the user enter 1234
the output should be 4,3,2,1,
how can i edit the code to remove the comma after the last num?
something like 4,3,2,1
Since everyone is having a field day, here's mine:
while (number > 0) {
System.out.print( number % 10 + ((number/=10)>0 ? "," : ""));
}
This is the most elegant approach I have picked along the way:
String delimiter = "";
while (number > 0) {
System.out.print(delimiter + number % 10);
number /= 10;
delimiter = ",";
}
I would do the following
if (number > 0) {
System.out.print( number % 10 );
number = number / 10;
while (number > 0) {
System.out.print("," + (number % 10) );
number = number / 10;
}
}
Print the first element and then for all the other ones prepend a ,. In this way, you always end with a
, X
The other options are doing unnecessary if checks.
I would do it this way
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
if (number > 0)
System.out.print(",");
}
This could do the trick:
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
if(number!=0) System.out.print(",");
}
Sotirios's solution works but here's an alternative:
// replacing "scan" with an example number.
int start = 123456789;
for (int number = start; number > 0; number = number / 10) {
if(number < start)
System.out.print(',');
System.out.print(number % 10);
}
This will DRY up the calculation of the count down (number/10) but does the test to see if it's not the first one in each loop. I think that that test, however, would turn out to be faster than doing string arithmetic ("," + (number % 10)).
Hope this helps.
int x;
Scanner scan = new Scanner(System.in);
System.out.print("Enter integer : ");
x = scan.nextInt();
for(x = 4; x>1; x = x-1)
{
System.out.print(x + ",");
}
if (x != 0) // this is so the last number doesn't end with a comma
{
System.out.print(x);
}
All the code that was showed here is invalid because the user can enter 0 and 0 should be printed out.
The valid code will look the following way
do
{
System.out.print( number % 10 );
number = number / 10;
if ( number != 0 )
System.out.print( "," );
} while ( number != 0 );

Categories