If statement not working, skipping over to else - java

My "if" statement doesnt seem to be working, whatever I put in always seems to default to my "else" statement. Such as if I put in the integer "1" or "2", which have "if" statements associated with them, it still defaults to "else". Any help would be appreciated :)
String number = JOptionPane.showInputDialog("Would you like a custom loop count or an infinite? 1. Custom 2. Infinite"); //test choice
n = Integer.parseInt(number);
while (n < 0 || n > 2) {
if (n == 1) {
String number2 = JOptionPane.showInputDialog("How many times would you like to loop?");
integer = Integer.parseInt(number2);
while (integer < 0) {
while (x < integer) {
g.drawString("hi", 200, y);
x += 1;
y = y + 40; //test
}//end while
}
}//end if
else if (n == 2) {
while (1 == 1);
}//end if
else;
}
g.drawString("Please pick a valid choice", 200, 200);

If the block after
while (n<0 || n>2)
is executed, you know that n is either < 0 or > 2. Therefore it can't be equal to 1 or 2 and the else block is executed, which happens to be empty because it is followed by a ;.
That's not mentioning the few weird statements found in your code ;-)
ps: I have edited your post to add proper indentation to your code and include { and }. It might look a little clearer now.

else;
That's very wrong.
You don't have a else statement, it means the following line of code is executed.
This line is very bad too :
while (1==1);
Please indent following the norms and remove the unwanted ';'.

Related

Diagonal Stars problems

I'm a total begginer in java and I'm having some trouble at understanding how things work... could someone explain to me why the computer understands "i" as horizontal row and "j" as vertical row since both "for" loops are the same, just with different variables?
public class DiagonalStar {
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
} else {
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number; j++) {
if ((i == 1) || (j == 1) || (i == number) || (j == number) || (i == j) || (j == number - i + 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
It's actually not a matter of vertical or horizontal, is based on the order the lines of code are executed.
For example:
for(int n=0;n<10;n++)
{
System.out.println(n);
}
Would print
0
1
2
3
4
5
6
7
8
9
But if you put another loop inside it, it will execute it before passing to the next loop of n.
for(int n=0;n<10;n++)
{
for(int m=10;m<15;m++)
{
System.out.println(n + "." + m);
}
}
That would print
0.10
0.11
0.12
0.13
0.14
0.15
All that before getting to 1.10, 1.11, etc...
So when you're printing the "*" you're just looping in that logic, and whenever you complete the inner for you use println (that prints the next line)
I would suggest messing with the variables, see what the program outputs when you switch i with j or when you change the conditions.
Good luck!
You have nested one for loop into another. This means that for each value of i you are going thru all values of j.
After inner loop you have System.out.println() and this moves you to another row.
println() - prints text with a newline
print() - just prints text
System.out.print prints in a row, while System.out.println prints in a column

Using modulus operator in for Loop with if statements - Java beginner

I hope someone can help. My problem is with using the modulus operator in a for loop. My code is as follows:
for (int i = 0; i < 10; i++)
if (i % 2 == 0) {
method1();
}
else {
method2();
}
I understand how this loop works in that it iterates between if and else because of the even and odd numbers created by the condition that uses
the modulus operator (i % 2 == 0)
However, I want to create a condition using the modulus operator so that my loop iterates through 4 methods - as in:
loop starts{
method1();
method2();
method3();
method4();
loop repeats
}
I can't work out how to accomplish this. I would appreciate any help and advice.
Thanks in advance.
Put j = i % 4
And check for method1() j should be equal to j = 0, similarly for
Method2() check j = 1. And so on. Put for range conditions to 1 for infinite loop or desired range.
You could be looking to use the switch statement. More on that here.
Basically it takes a variable to switch between cases.
For example:
for(int i = 0; i < 10; i++){
switch(i%2) {
case 0: method0();
break;
case 1: method1();
break;
}
}
Here is the out put if method0 printed 0, and method1 printed 1:
1
0
1
0
1
0
1
0
1
0
You can edit the modulus to whatever number you want, you just have to account for the different possibilities.
Do you mean something like this?
for(int i = 0; i < 10; i++)
{
if(i%4 == 0)
{
condition
}
else if(i%4 == 1)
{
condition
}
else if(i%4 == 2)
{
condition
}
else if(i%4 == 3)
{
condition
}
}
Remember to put it on paper if you're confused and loop through your head (as a beginner)

Getting a while loop to continue with a if statement

I'm working with a while loop and an if statement.
I want the loop to continue if the else statement is being run. In my understanding the "continue;" should restart the loop, but it doesn't.
I found one workaround to fix this though, it's to set "cho = 1;". But is this really necessary? Are there any more logic ways to solve this problem?
Thanks!
while (sum < 21 && cho == 1 && sum != 21) {
System.out.println("Do you want to (1)hit or (2) stay?");
cho = scan.nextInt();
if (cho == 1) {
getCard(index++);
if (sum > 21) {
System.out.println("You busted! Dealer wins.");
return;
}
} else if (cho == 2) {
System.out.println("Your value is " + sum);
sum = playerTotal;
}
else{
cho = 1;
System.err.println("The input value given is not a valid integer");
continue; //Does not restart the loop.
}
}
A continue jumps back to the condition of the loop which is then evaluated again. If the condition evaluates to false, the loop will obviously not be run again.
So if you want your loop to continue actually looping, you have to make sure that the condition is true.
This means: You have to set cho = 1 and make sure sum < 21
Also note that the sum != 21 in your condition is not needed, since sum < 21 already eliminates that possibility.

Writing a while loop to find multiples of 7 from 1 to 9999

I am trying to write a while loop like the question indicates that returns the multiples of 7 in decreasing order. At first I was trying to just write a code to return the values before I made then decreasing, but my while loop won't execute. I added a statement printing "Start" just to make sure it was running.
System.out.println("Start");
int number = 7;
int count = 9999;
while (number <= count);
{
System.out.print(number);
number = number + 7;
}
I wrote it this way to be simpler and because I was unsure of how to make number into a string of values and check each one. Any help on this is appreciated. Thank you!
**RESOLVED. Sorry first time on site and I am not sure if there is another way to close this, but thanks to multiple users point out the semi colon and Vikas pointing out the println error, the code runs. As to making it decreasing I just swapped a few things around:
System.out.println("Start");
int number = 9999;
int count = 7;
while (number >= count)
{System.out.println(number);
number = number - 7;
}
}
You have an extra semicolon after the while(). Remove it.
With the semicolon at the end of this line, the while loop has an empty body. The following statements in curly braces are executed after the loop has finished. But the loop will never finish, because the condition is always true, because number never changes.
while (number <= count);
Change it to:
while (number <= count)
{
...
}
You are not able to see the output value for number because it is println and not print
System.out.print(number);
Change this to
System.out.println(number);
And also as others have answered, remove the semi colon ; at the end of while loop.
Having said this, since you want the result to be printed from Descending to Ascending use below code,
System.out.println("Start");
int number = 7;
int count = 9996;
while (number <= count)
{
System.out.println(count);
count = count - number;
}
You have a semicolon at the end of your while loop:
while (number <= count);
which will make it an empty loop. And the following curly braces will only act as a code block and not loop
int count = 9999;
while (count >= 1) {
if (count % 7 == 0) {
System.out.println(count);
}
count--;
}
I used this code and it also worked
System.out.println("Start");
int number = 9999;
int count = 7;
while (number >= count){
if(number%7==0)
System.out.println(number);
number--;
}}}

Atoi in Java for negative values

I am writing an Atoi function in Java. It runs fine for +ve integers. But what I want is when I enter a negative integer it should give me an error. So I tried including continue statement in my class Atoi. The class implemented is:
class Atoi {
int atoi(String tmp) {
int result = 0;
for (int i = 0; i < tmp.length(); i++) {
char digit = (char)(tmp.charAt(i) - '0');
if(digit == '-')
continue;
}
else {
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
}
return result;
}
}
But unfortunately it gives me the negative equivalent of the character i.e for -12 it gives me 655312! Help.
EDIT: Suppose I need to check for floating point numbers what should I do? If I enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!!
Instead of continue you should give an error (throw an exception, return -1 or whatever you mean with "give an eror").
If you want to ignore the - you can change the else clause to:
result = digit + result * 10;
Quick fix for the obvious problem: the order of the logic was wrong...
Instead of
char digit = (char)(tmp.charAt(i) - '0');
if(digit=='-')
continue;
try
char origChar=tmp.charAt(i);
if(origChar=='-')
continue;
char digit = (char)(origChar - '0');
But there are two more problems:
it does not negate the value, in case of a '-' character is present!
what if this is the input string: -1-2-3-4-5? The result will be interesting! EDIT: try this input also: 'répa'... Even more interesting result!
Don't forget to test with incorrect inputs too, and as #Klaus suggested, don't hesitate to throw an exception, (preferably IllegalArgumentException) with a correct error message, if an incorrect input is given to the function...
If this is not being done as a programming exercise, there is a simpler solution:
static int atoi(String tmp)
{
int result = Integer.parseInt(tmp);
if(result >= 0) {
return result;
} else {
throw new IllegalArgumentException("Negative string "+"\"" + tmp + "\"");
}
}
Substitute the appropriate exception or other action in the negative result case. If you want to just ignore '-', as in the posted code, replace the if-then-else with:
return Math.abs(result);
This code also throws an exception for strings like "abc".
More generally, if a library method does not do exactly what you want, it is often easy to use it in a method that modifies its behavior, rather than re-writing it.
You can write code like this, of course, but you need to check that tmp is a valid number.
int atoi(String tmp) {
int result = 0;
int factor = tmp.charAt(0) == "-" ? -1 : 1;
for (int i = 0; i < tmp.length(); i++) {
if (tmp.chatAt(i) < '0' || tmp.chatAt(i) > '9')
continue;
char digit = (char)(tmp.charAt(i) - '0');
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
}
return result * factor;
}
if(digit=='-')
With
(char)(tmp.charAt(i)
You're code is assuming there are no -'s
(char)(tmp.charAt(i) - '0');
Is an optimization that's blindly clamping the 'digit' variable to a number.
You need to step through what your code is actually doing, search for an ASCII chart and work through what the subtractions of '0' does ('0' == 48), so '1' (49) - '0' (48) = 1 etc...
If you don't want to convert negative numbers then simply return 0 whenever you encounter - sign instead of looping further. Put this code before the if-else block.
if(tmp.charAt(i)=='-')
return 0;

Categories