I am trying to print a pattern through java. I am using for loop and a conditional statement but there is some problem with && operator. I am not getting why it is behaving strange with my code specially. Following is my code.
public class Test{
public static void main(String ar[]){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
output
unknown#unknown-Lenovo-E40-80:~/Desktop/java_test$ javac Test.java
unknown#unknown-Lenovo-E40-80:~/Desktop/java_test$ java Test
****
****
****
****
above output is totally different to my expectation. line 1 is not printed why? i just wanted to skip (i=0 and j=0) location's element.
Let's see what happens:
For line 1 you get i = 0 and j = 0 to 4, thus you'll get 5 spaces (because i = 0 will always end up in the result being false).
For all other lines i is != 0 and j is still 0 to 4 so you get 1 space and 4 stars.
If you change the space you print to a underscore you'd get the following output:
_____
_****
_****
_****
_****
i just wanted to skip (i=0 and j=0) location's element
Currently you are skipping all elements that don't have any of their indices being 0 (i != 0 && j != 0 translates to "i is not 0 and j is not 0").
If you only want to skip that one element you need to either change the expression to if( i == 0 && j == 0) { skip } or if( !(i == 0 && j == 0) ) { do_whatever_you_need } where the second translates to "if not both i and j are 0" (note that this means that either one can be 0, only the combination of both satisfies the condition).
Line 1 is getting printed, but it is printed with spaces.
The reason is because you are checking (i != 0 && j != 0). In the first iteration of the outer loop i is 0, hence the control goes to the else block.
Boolean algebra says that !a && !b == !(a || b). You are trying to say that !a && !b == !(a && b).
Your test of
if((i!=0 && j!=0))
is equivalent to
if(!(i==0 || j == 0))
This is not what you want, according to your final statement: "I just wanted to skip (i=0 and j=0) location's element."
And so, you can alter your test in a few ways. The first is probably easiest - reverse the blocks. This has the fewest operations and is easiest to understand.
if (i==0 && j==0)
System.out.print(" ");
else
System.out.print("*");
Or, if you want to maintain the order, alter your if statement. To invert your requirement of (i==0 && j==0): !(a && b) == (!a || !b)
if( (i!=0) || (j!=0) )
System.out.print("*");
else
System.out.print(" ");
The first line prints whitespaces, as I added in the comment, because, at this point i == 0 and prints it 4 times, but the second, third, and others attempts will print at first because will be equals to zero j == 0 after that four *
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
} else {
System.out.print(" "); //THIS IS PRINTING THE FIRST LINE
}
}
System.out.println();
}
In first line i=0 so in first iteration of i control goes to else part and in first row spaces are printed instead of asterisks. And on every iteration of i first index j=0. So again else part executes and in first column again spaces are printed instead of asterisks. And on all other places asterisks are printed.
public class Test{
public static void main(String ar[]){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if((i!=0 && j!=0)){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
Related
I’m a senior in high school taking a computer science class. For homework, we have to create solutions to certain CodingBat (practice coding website) problems. I am experiencing problems with this question, some of which include OutOfBounds for the array. Based on my code, I can’t quite figure out why this is happening. The following attached code (below) is what I have created as a solution to the CodingBat problem for unlucky1 in Array-1 (java), which describes the challenge as: “We'll say that a 1 immediately followed by a 3 in an array is an "unlucky" 1. Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.
public boolean unlucky1(int[] nums) {
int i = 0;
for(i = 0; i < nums.length; i++)
if(nums[i-1] == 1 && nums[i] == 3)
{
return true;
}
return false;
}
The problem statement is "Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.", so you don't even need a loop - you just need to examine the first two and last two elements of the array:
public boolean unlucky1(int[] nums) {
return nums != null &&
nums.length >= 2 &&
(nums[0] == 1 && nums[1] == 3 ||
nums[nums.length - 2] == 1 && nums[nums.length -1] == 3);
}
The following code is the correct method.
0.public static boolean unlucky1(int[] nums){ //Firstly,declare the method
"static"
1. int length = nums.length;//Get the array length.
2.if((nums[0] == 1 && nums[1] == 3) && ( nums[length - 2] == 1 &&
nums[length] -1 == 3)){
3. return true;
}
4. return false;
}
In row 2,your code was: "if(nums[i-1] == 1 && nums[i] == 3)";
It showed arrayoutofbound because the starting array index is 0 and you decalred in the if statement
" if(nums[0-1]...)which says if nums[-1] which is out of bounds."
Also to check the last 2 numbers of the array you do the following:
( nums[length - 1] == 1 && nums[length] == 3)) where :
" nums[length - 2] == 1"
checks 1 value before the last array value
and
" nums[length] - 1 == 3 "
checks the last array value
I'm currently learning java in my online classes and I'm learning about loops (specifically continue and break statements). The example given to me was:
int j = 0
while (true){
System.out.println();
j++;
System.out.print(j);
if (j%2 > 0) continue
System.out.print(" is divisible by 2");
if (j >= 10) break;
}
I don't understand why its (j%2 > 0) and not (j%2 == 0) because what if 'j' is 5 for example and you do 5%2. Wouldnt the number you get be 1? Or am I missing something? Can someone please explain this to me?
(sorry is I'm not my question is a little confusing. I've never used this site before and I'm pretty young)
Let me explain to you. See the comments next to each line.
int j = 0
while (true){
System.out.println();
j++; //increases the value of j on the next line by 1.
System.out.print(j); //prints 1, the first time because of above, 0 + 1.
if (j%2 > 0) continue //using modulus operator(%) we are doing 1 % 2, answer is 1
//since 1 % 2(if 1 is divisible by 2) > 0 we are
//continue statement breaks the iteration in the
//loop, so anything below this line won't be
//executed.
System.out.print(" is divisible by 2");//this line will only be executed
//if j is divisible by 2. that is
//j is divisible by 2 (j%2 == 0)
if (j >= 10) break; //when j is equal or greater than
//0 we are stopping the while loop.
}
Continue means "go to the top of the loop, skipping the rest of the loop's code" not "continue with the code". So since 5%2 is 1, and 1 > 0, the continue will execute, going directly to the top of the loop and skipping the rest of the body.
Why do they use > 0 instead of != 0? There isn't any technical reason, its a style difference. I personally would have used the latter as its more clear in my mind. But either works.
int j = 0;
while (true){
System.out.println();
j++;
System.out.print(j);
// in this case you won't print any message and you
// are sure that the next number is even (j will be incremented by "continue;").
if (j%2 > 0) continue;
System.out.print(" is divisible by 2");
if (j >= 10) break;
}
X % 2 means the remainder when is x is divided by 2. So if the remainder of x/2 is more than 0, it means that x is an odd number. When x%2 == 0, then x is a positive number
I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 )
System.out.println(i);
if (i%3 == 0){
System.out.println("ÒFizzÓ");
}else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
}
}
Eclipse tells me that "i" cannot be resolved as a variable. This is confusing to me as I thought I already defined "i" as an integer in my for loop? Thanks for taking the time to solve this newbie question :)
Add braces or your loop body ends after the first statement. Also, for your approach you need to test 15 first because it's a multiple of 3 and 5
for(int i = 0; i < 101; i++) { // <-- i++ is short for i = i + 1
System.out.println(i);
if (i % 15 == 0) {
System.out.println("ÒFizzBuzzÓ");
} else if (i % 5 == 0) {
System.out.println("ÒBuzzÓ");
} else if (i % 3 == 0) {
System.out.println("ÒFizzÓ");
}
}
I know a funny story about Apple who lost a few million dollars because a developer updated a code with an if block but... the if statement had only one instruction and no curly brackets and he did not see it. Thus, the code he was willing to add when the condition was met were actually ALWAYS executed.
In your case, you won't lose money but you surely did the same mistake :
for(int i = 0; i < 101; i= i +1 ) {
System.out.println(i);
if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
} else if (i%3 == 0){
System.out.println("ÒFizzÓ");
} else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}
}
When Java says something cannot be resolved as a variable, it is usually been used outside the scope it was declared or it was not declared at all.In your case, your braceless for-loop is causing the problem.
I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 ){
System.out.println(i);
if (i%15 == 0){
System.out.println("ÒFizzBuzzÓ");
}else if (i % 3 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 5 == 0){
System.out.println("ÒFizzÓ");
}
}
}
It seemingly runs fine, but on closer inspection of the output, the "Fizz" and "Buzz" lines are printed AFTER the relevant numbers and are not printed as a replacement of the numbers
For example, I get the below
9
ÒBuzzÓ
10
ÒFizzÓ
11
12
ÒBuzzÓ
13
14
15
ÒFizzBuzzÓ
16
How do I get the relevant numbers to be replaced by the correct string statements instead of what I currently have? I only managed to find tips on converting strings to integers, but not replacement of integers to strings on SO, so I would appreciate any help :)
Move printing of number in else part of your if else ladder as like:
for(int i = 1; i < 101; i= i +1 ){
if (i%15 == 0){
System.out.println("ÒFizzBuzzÓ");
}else if (i % 3 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 5 == 0){
System.out.println("ÒFizzÓ");
} else {
System.out.println(i);
}
}
I am new to processing and I am having trouble with this. I keep getting an error message for the bolded part of the code below. Is my syntax wrong?
void block(int x, int y, int s, color tinto) {
fill(tinto);
for (int i = 0; i < 3; i++) {
triple(x, y+i*s, s, tinto);
}
if (0 < i < 3 && 6 < i < 9) { // HERE
tinto = 255;
}
else {
tinto = tinto - 200;
}
}
In Java, to check if a variable is in a range you have to divide the statement into two parts, like this:
if (0 < i && i < 3 && 6 < i && i < 9){
}
This specific code will never be true, however, because you're asking for it to be in two different ranges. Perhaps you meant to check for either range?
if (0 < i && i < 3 || 6 < i && i < 9){
}
Note the || or operator instead of the && and operator.
The syntax is not valid, and I think you're expression is wrong anyway. You say i has to be within a range AND within another. I think you mean to write that it could be between one OR the other.
Example of valid syntax: instead of 0 < i < 3, write i > 0 && i < 3.
Try this:
if ( (i > 0 && i < 3) || (i > 6 && i < 9) )
Note that the following (which is what you were trying to do apparently) will never be evaluated to true because it cannot be within both ranges.
if ( (i > 0 && i < 3) && (i > 6 && i < 9) ) // incorrect
This isn't valid java expression. Try:
if (0<i && i<3 && 6<i && i<9){
There are two different problems with this code snippet. First, you have defined the 'i' variable as in "int" inside of the for loop. This instance of 'i' is no longer defined once you exit that for loop -- so the if statement below does not refer to that instance. To overcome this, define 'i' before the for loop...
int i;
for ( i=0; i<3; I++ ) {
...
}
if ( i ...
which brings me to the second error. The syntax "0 < i < 3" is not correct. In c/c++ the operators are executed one at a time ... so in this case the first "<" operator will be evaluated as "0 < i" and the result will be a Boolean (which will always be 'true' in your particular code snippet). But the important point is that the result is a Boolean. Next the code will attempt to evaluate that result with the next part of the statement -- "true < 3", which just doesn't make any sense, and so that receives a compiler error.
In your code snippet, there is no exit to the for loop until the value of i reaches 3, so this second "if" statement is unneeded. But if you did want to test to see whether i was between 1 and 2 (inclusive), then you would have to break those up into individual tests...
if ( 0 < i && i < 3 ...
Lastly ... if the value of i is between 1 and 2 (inclusive), then it cannot also be between 7 and 8 (inclusive) .. therefore the if statement as you coded it will always be false even after we correct the syntax.