Do-while and Exception Hadnling - java

package learnjava;
import java.util.Scanner;
public class exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x =1;
do {
try {
System.out.println("Input first number : ");
int n1 = input.nextInt();
System.out.println("Input second number : ");
int n2 = input.nextInt();
int sum = n1 / n2;
System.out.println("result = "+sum);
x = 2;
} catch (Exception e) {
System.out.println("Error");
}
} while (x == 1);
}
}
I watched java tutorials in thenewboston.....
I want ask you...why x=2...?can you explain why?...thanks

This a code doesn't approach it's own concept well.
Nonetheless Do-While is a exit control loop and is keeps on executing the loop till x is not equal to any number except 1. That is if there is any change in x apart from being 'x = 1'then the loop would break as in the loop will stop functioning. Here we are using a try catch to prevent any number being divided by zero and we use x=2 to execute the loop once and exit.
Anyway this is concept builder, but this is not how one would approach this methodology.

do-while loop executes once without checking the condition.
In this case the condition to continue while loop is x == 1 . That is because you have set x = 1 in your code above.
While executing prior to checking the condition, using the scanner, you read 2 integers and done some operations on them and printed the result.
As the logic expects flow to stop here (that is just reading 2 integers and printing result), x has been set to 2 that is x = 2.
Now answering your question why x = 2. It can be anything other than 1 which will terminate the while loop and not allow any further iterations.

this code do division if you inter the n2 value to 0, exception happened and printed the error and the x=1 value was not changed the while condition is true and your code running again and want the input. if your input was true (n2!=0) your operation done and the x value changed to two x=2. when the while condition checked the result is false and break the do while loop.
I write some comment in your code.
package learnjava;
import java.util.Scanner;
public class exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x =1;
do {
try {
System.out.println("Input first number : ");
int n1 = input.nextInt();
System.out.println("Input second number : ");
int n2 = input.nextInt();
int sum = n1 / n2;//if your n2 input was 0 exception happened and go to catch block.
System.out.println("result = "+sum);
x = 2;// if one time your code execute without exception the x changed to 2. if exception happened your code execute again.
} catch (Exception e) {
System.out.println("Error");
}
} while (x == 1);
}
}

Its simple,
The do while works this way.
First the do part gets executes, if the condition in the while loop is satisfied, the do loop executes again. This will go on, till the condition in the while loop is not satisfied.
do {
//work is done.
//now lets us change the condition so that we can get out of this do-while loop.
// this condition is nothing but setting x equal to nay value other than 1. It can be 2 or 10000 or -1.
} while (x == 1);
So here once the functionlity of the do loop is satisfied, the x==2 is done. This makes sure that the condition in while is not satisfied and hence the code exists do-while loop.

Related

I want to add the a feature where the program to ask the user if they want to continue

I want to add a feature to my while loop if they want to try again but I don't know where to put the code. If the user enters N, the code shall stop and if he enters Y, it shall re-ask for the start, end and step.
import java.util.Scanner;
public class Sum3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int start, end, step;
char option;
System.out.print("Enter START value: ");
start = input.nextInt();
System.out.print("Enter END value: ");
end = input.nextInt();
System.out.print("Enter STEP value: ");
step = input.nextInt();
while (start > end)
System.out.println("Start is larger than End");
while (step == 0)
System.out.println("Step is larger than the zero");
while (true)
for (int i = start; i < end; i += step)
System.out.println(i);
/*System.out.println("Would you still want to continue? (Y/ N)");
option = input.next().charAt(0);*/
}
}
I can see a few significant problems in your code.
Like all of your while loops are infinite. You can just use "if-else" instead.
Next, I'm not sure why you put that for loop inside that endless while loop.
What you can do instead is, do your printing inside for loop and then ask if they want to retry. Here's an example :
for (int i = start; i < end; i = i + step)
{
System.out.println(i);
System.out.println("Retry (Y/N) : ");
option = input.nextChar();
if (option == 'N')
{
break;
}
}
You can add a do-while loop and put all your logic within it. So basically it should begin before your first sysout and should end after your commented code at the end.
But there are some other problems in your code. For example,
while(step == 0) should be if(step == 0) or better if(step <=0), because you want to show the message if step is 0 or negative, otherwise you want to print the numbers, correct?
You don't need the while(true) around the for loop. For loop itself should be enough.
Take this as a suggestion and build around your code.

Scanner is trying to read more numbers than expected and skips some other numbers

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter numbers, input ends with 0: ");
int max = 0;
int count = 0;
while (scanner.nextInt() != 0 )
{
if (scanner.nextInt() > max)
{
max = scanner.nextInt();
count = 1;
}
else if (scanner.nextInt() == max)
{
count++;
}
}
if (max == 0 && count == 0)
{
System.out.println("No numbers are entered except zero.");
}
else
{
System.out.println("The largest number is " + max);
System.out.println("The occurence count of the largest number is " + count);
}
}
}
The above code is what I have managed to create thus far in an attempt to create a program that will identify the largest number, and also take a count of how many times that number is listed. I would also like the number 0 to trigger the end of the input sequence.
For example, if I type:
2 3 9 4 5 9 3 3 0
I should receive a max of 9 and a count of 2.
The code seems to work sometimes, and other times does not return any output when a sequence ending in 0 is entered. I also get an incorrect count but correct max other times.
Please help me understand what is going haywire with my code.
Every time you invoke scanner.nextInt(), it's (waiting for and) reading another int from input.
The times when it doesn't seem to complete is when you enter a sequence without a multiple of 3 entries, e.g. 1 0: the while condition reads the 1; the if condition reads the 0 (which doesn't cause the loop to break); and the max = waits for you to enter another number.
Don't keep invoking it: assign int next = scanner.nextInt(), and use that value:
while (true) {
int next = scanner.nextInt();
if (next == 0) break;
if (next > max) { ... }
else if (next == max) { ... }
}
#Mind you that as far as your while loop is concerned, no command in the while loop will be executed whenever you enter zero[0] as an input because what you instructed the while loop to do is to run when the input is not zero so no need putting a condition to check whether an input is zero or not.
Then just as #Andy Turner said with small editon to his code do this to get things done:
//use the value "true" rather than any other condition to keep the loop in iteration.
//The boolean value "true" means continue reading and accepting input forever unless there is a condition that will break out of it inside the while loop
while (true) {
int next = scanner.nextInt();
if (next == 0){
//Do your prefered stuff here when the input evaluates to zero and then break out of the loop.
break;
}
if (next > max) { ... }
else if (next == max) { ... }
}

How can I input an if statement inside a while loop?

import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.
If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.
The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.
The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}
To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)
You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

Could anyone tell me why my program doesn't work?

The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out.
So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.
import java.util.Scanner;
public class Testing3{
public static void main(String[] args) {
int sum1 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
String number = input.nextLine();
int value =Integer.parseInt(number);
while(true) {
if (value!=0) {
number = input.nextLine();
if (Math.round(value)==value)//condition to integer{
sum1 = sum1 + value;
} else {
System.out.println(sum1);
break;
}
}
}
}
First of all, use while(true) or for(;;) to make in infinite loop
Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt.
Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.
Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:
number = input.nextInt();
if (number != 0){
sum1 = sum1 + number; //or use sum1 += number
} else {
System.out.println(sum1);
break;
}
I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.
Let's say we have a double variable called x and this evaluates to true if x is an integer:
Math.round(x) == x
I don't know whether there is a better way to do it but that's how I would do it and I like it.

Java, Infinite loop- multiples of 2 only

I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}

Categories

Resources