Termination of program using if else statement? - java

trying to terminate program using negative numbers and if else statement . does anyone see whats wrong with this thanks.
import java.util.Scanner;
public class Assignment {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
int backUp = n;
if(n>0)
n=n/10;
i++;
else if(backUp = -1)
System.out.print("program terminated......");
System.exit(0);
System.out.println("Number of Digits in " +backUp +" is " +i);
}
}

First of all, = is for assigning values. Use == for comparing.
Also, you need to use {} after if and else statements if you want to run more than one line.

else if(backUp = -1)
Should be
else if(backUp == -1)
= assignment operator , == is for comparing
And finally with missed {}
if (n > 0) {
n = n / 10;
i++;
} else if (backUp == -1) {
System.out.print("program terminated......");
System.exit(0);
}else{
// do something else. I have no idea.
}

You are missing { } for your if-statements. In if statements without the { }, only the line following the if-statement will be affected by the outcome of the if-test.
So:
if (condition)
doSomething();
doSomethingElse();
will execute doSomething() if condition == true and doSomethingElse() no matter if condition == true.
if (condition) {
doSomething();
doSomethingElse();
}
will execute both doSomething() and doSomethingElse(), if and only if condition == true.

You are using an assignment operator to evaluate a condition.
else if(backUp = -1)
should be
else if(backup == -1)

remove else use if(backup==-1).

First of all your indenting.
Secondly, if you want to execute multiple statements given a certain condition you'll need to put it in a code block like if(x) { /* do multiple things */ }.
Thirdly, your else if(backUp = -1) is invalid because you need a boolean expression inside a if, backUp = -1 is an assignment and thus does not evaluate to a boolean (you probably want backUp == -1).
And you probably want to loop the n = n/10; i++; part because now it will never count more than 1 digit.

Related

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

Loop certain IF statements in java

import java.util.Scanner;
public class main {
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of sides");
number = input.nextInt();
if (number == 1) {
System.out.println("Circle");
}
if (number == 3) {
System.out.println("Triangle");
}
if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
}
}
Hello, I am trying to use the if statement. Can anyone advise me how to loop if statements? Because I get this as a result for example:
circle
Incorrect Input.
Also, How could I repeat the scanner so it allowed me to type another input?
Currently, the else clause is only associated to the last if block i.e. if (number == 4) {...} This means if any of the other if blocks are executed, it will still print "Incorrect Input". The solution is to use else if instead of separate if's.
if (number == 1) {
System.out.println("Circle");
}else if (number == 3) {
System.out.println("Triangle");
}else if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
You can use switch case (see : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html).
And you can check the type of number or string with instanceof.
For your second part question, I guess you're looking for something like a do....while loop, you can set up some condition like if the input result is not a number, then it will stuck in the loop until the user type in a number then only go in the the if, else-if statement

Is it possible to use a boolean expression in this manner?

I am currently learning java script and attempting new things, for example I wish to see if I can set a boolean expression to end if it detects a starting number through an ending number.
Or in other terms what I'll want is 3 through 8.
I will make it clear I am using netbeans IDE.
Within my last else if statement, I want it to end the asking process. I am hoping it is a simple fix, but I can not think of anything that will accomplish this unless I create a lot more else if statements.
Scanner input = new Scanner(System.in);
int[][] table;
boolean stopasking = true;
while (stopasking = true){
System.out.println("Let's make a magic Square! How big should it be? ");
int size = input.nextInt();
if (size < 0)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size >= 9)
{
System.out.println("That's huge! Please enter a number less than 9.");
System.out.println("");
}
else if (size <= 2)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size == 3)
{
stopasking = false;
}
}
You have used the assignmnent operator =
you should use == instead
also the condition size<=2 holds when size<0 so you can use one if for both
while(stopasking){
if (size <= 2) {
System.out.println("That would violate the laws of mathematics!\n");
} else if (size >= 9){
System.out.println("That's huge! Please enter a number less than 9.\n");
} else if (size == 3){
stopasking = false;
}
}
you can use the boolean expression in this way, as condition to exit from a loop. Some would say it is a more elegant solution than break.

Is the following flowchart correct for the given code?

I have designed a flowchart that is based on this code in Java.
public static void main(String args[]) throws IOException {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object = new attendance_and_student_management();
int flag = 1;
do {
{
int var = object.menu();
if (var == 1) {
System.out.println("\f");
object.add_student();
System.out.println();
} else if (var == 2) {
System.out.println("\f");
object.search_student();
System.out.println();
} else if (var == 3) {
System.out.println("\f");
object.change_student_information();
System.out.println();
} else if (var == 4) {
System.out.println("\f");
object.take_attendance();
System.out.println();
} else if (var == 5) {
System.out.println("\f");
object.attendance_summary();
System.out.println();
} else if (var == 6) {
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
} else if (var == 7) {
System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
} else {
System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int choice1 = Integer.parseInt(bw.readLine());
if (choice1 == 1) {
continue;
} else {
break;
}
}
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag = Integer.parseInt(bw.readLine());
if (flag != 1) {
System.out.println("Are you sure you want to exit? Press 1 for Yes");
int flag2 = Integer.parseInt(bw.readLine());
if (flag2 == 1)
flag = 0;
else
flag = 1;
}
}
}
while (flag == 1);
}
The flowchart is given below:
I am still learning how to construct flowcharts, therefore, I am not sure whether this diagram is correct. Any inputs or suggestions will be much appreciated.
PS: I tried to make the flow chart a bit simpler, please do tell if this is more appropriate than the previous one...
Your condition on the chart
Is var equal to 1,2,3,4,5,6 or 7?
ist not 100% right.
Your program works with if and else if conditions, which check each condition serial. You first check the 1, then the 2, then the 3 and so one...
Your chart shows this conditions as an All-In-One condition, what in java mean a switch).
So your chart should show these if's more like this:
Next, you dont need to draw the chart-boxes
Execute Method
In your code, you can draw just one box for the action in a true if-condition (like my added image).
And finally, you should have only one "Exit / End" point on the chart. Each flow that stopps the program, should link to this End-Point.

Java program exit function not working

i'm a newbie to java so i decided to create a simple program that prints out even numbers. I tried to make it exit a while loop if you answered no to the question but it just keeps on going.
Here's the code
public static void main(String[] args){
String continueYorN = "Y";
int i = 0;
while (continueYorN.equalsIgnoreCase("y")){
while(i >= 0){
i++;
if((i%2) == 0){
System.out.println(i);
continue;
}
System.out.println("Do you want to generate another even number?");
continueYorN = userInput.nextLine();
}
}
}
Your loop has no break condition (i.e, something that stop the loop in some condition), so it will continue forever.
You should replace the inner while with something like that:
while(i >= 0){
i++;
if((i%2) == 0){
System.out.println(i);
break;
}

Categories