While Loop and difficulties - java

I am a beginner in Java and had a question regarding an assignment I was doing.
I am trying to read a sequence of integer inputs and print out the largest and the smallest number. Though I already wrote the code, but the problem is that when I run it, it doesn't print the largest nor the smallest number. The code seems right even though its not! Any help would be appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
while (in.hasNextInt()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println();
}
System.out.println(largest);
System.out.println(smallest);
}
}

To Stop Waiting for an input :
Enter A character as input : in.hasNextInt() return False

Your code will not stop accepting numbers until it get something other than a number.
Like a alphabetical character. Enter an alphabetical character or keep something as a terminator.
Like enter -99 to quit or something.

Reading the code I would say that you expect the user to enter a set of numbers separated by space (the default separator chosen by the Scanner)
The scanner will loop endless parsing the input.
Now you need to decide a condition to exit and make your code safer.
When I say make your vode safer I mean put a try catch around your code in case the user doesn't write a number. Moreover you should close the scanner in a finally.
If you write something like the code below, the cycle is broken whenever u write a letter. E.g 1 2 4 6 A will print 2 and 6. Take it as a suggestion to work out a bit. Actually. you need to still protect the first nextInt, which, as it is, could throw exception if you don't start with a number and ideally decide an exit character handling the other exceptions. But these are implementation details. The code below will work provided that you start with a number and finish with a character different from a number
import java.util.Scanner;
public class Practise {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
try {
while (in.hasNextInt()||in.hasNext()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println("Computing "+input);
}
System.out.println(largest);
System.out.println(smallest);
} catch (Exception ex) {
System.out.print("Exception caught: " + ex);
} finally {
in.close();
}
}
}

Related

Variable number of inputs - Java

Need a refresher. I'm sure I know this already but I'm wracking my mind for a more efficient way to do this:
In short, the user is asked how many inputs they'd like to input (up to a certain maximum). For example, let's say they say 10.
Next, they're asked to input a number of single-digit integers equal to the number of inputs they wanted to input (in this case, they'd put in 10 different single-digit integers).
My issue is that I haven't coded Java in a while so I'm rusty. My immediate thoughts go to two options:
int input1 = 0, input 2=0, input3=0 ... inputN=0;
use an array
While option 1 is incredibly sophomoric it gets the job done. I'm just unsure if there's a simpler way to do it without using arrays.
import java.util.Scanner;
public class Histogram
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 0;
boolean success = false;
//start of program
System.out.println("How many input values [max:20]?");
while (!success)
{
try
{
numInputs = keyboard.nextInt();
numInputChecker(numInputs);
success = true;
}
catch (Exception e)
{
keyboard.nextLine();
System.out.println("Single-digit integers only, please.");
}
}
System.out.println("Enter " + numInputs + " numbers.");
for(int i = 0; i < numInputs; i++)
{
// ?????????
}
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 20))
{
throw new Exception();
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer >= 10))
{
throw new Exception();
}
}
}```
i) If you're using multiple values, you're either going to need multiple variables or a collection of some sort. Agree with previous comments on choice of collection. (ii) If the amount of repetition required is counter controlled, why not set the loop to iterate that number of times? You would then need to nest while loops to ensure that your exception handling works but then you could limit the number of inputs. (iii) keyboard.nextInt() may be problematic because nextInt() does not discard the '\n'. It's better to Integer.parseInt(keyboard.nextLine()). (iv) If you're willing to work with strings, then you can do I/O once only and use the split() and Integer.parseInt() methods to get the necessary values.

How to stop a do while loop using "0" in java

I just wanted to say first that I'm a beginner so I apologize for my (really) horrible code.
I'm creating a program where you input an int and print out the square root using a do while loop. And when you input "0" the program will stop.
How do you stop it?
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
do {
System.out.println("Please enter an integer.");
int sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot==0);
System.out.println("Closing...");
InputNum.close();
}
}
You need to test if the value entered was 0 (I would test less than or equal to zero, because the square root of a negative number is imaginary). If so, break the loop. Like,
int sqroot = InputNum.nextInt();
if (sqroot <= 0) {
break;
}
try this
public static void main(String[] args) {
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
int sqroot = 0;
do {
System.out.println("Please enter an integer.");
sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot != 0);
System.out.println("Closing...");
InputNum.close();
}
I just initialize sqroot outside of your while and change == to !=
This academic exercise may demand use of a do/while loop, but if you're not constrained to using it, a for loop would also work:
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
System.out.println("Please enter an integer.");
for(int sqroot = InputNum.nextInt(); sqroot > 0; sqroot = InputNum.nextInt()) {
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
}
System.out.println("Closing...");
InputNum.close();
}
Your program as presented in the question has an intrinsic flaw: you ask for input and then immediately try and do something with it (calc the square root) without determining if it is suitable to use.
Switching to a for loop is one way this can be overcome, because it encourages a program flow of "ask for input", "check if input is acceptable", "use input", "repeat"
If you're constrained to using a do/while loop then you still need to follow this flow, which Elliott Frish addresses in his answer, recommending you add in the "check if input is acceptable" part as a dual purpose test of whether the input is <= 0.. Such values are not acceptable for a square root op, and you also want to end the program when you encounter them, so the test can be used to achieve both goals
Side trivia, for loops can be used pretty much exclusively:
for(;;) //same as while(true)
for(;test;) //same as while(test)
for(bool do = true; do; do = test) //same as do..while(test)
..though using while or do is probably more readable than using a for loop for the same job
Note, your while(sqroot==0) is a bug.. you don't want to continue looping while the user entered 0, you want to continue looping while they DIDN'T enter a 0...

Output of basic Java not printing. Can't figure out why

I'm a freshman at uni and we have to make an assignment where we have to find the second smallest number in a line of integers. Now I THINK I got it but I can't get the result to print. Can anyone figure out why this is?
package SecondSmallest;
import java.util.Scanner;
import java.io.PrintStream;
public class SecondSmallest {
public static void secondSmallestLoop() {
Scanner in = new Scanner(System.in);
PrintStream out = new PrintStream(System.out);
out.printf("Please enter a series of at least 2 integers: ");
int smallest = in.nextInt();
int secondSmallest = in.nextInt();
while (in.hasNextInt()) {
int next = in.nextInt();
if (next < smallest) {
secondSmallest = smallest;
smallest = next;
}
else if (next < secondSmallest) {
secondSmallest = next;
}
}
out.print("The second smallest number is: " + secondSmallest);
}
public static void main(String[] args) {
SecondSmallest.secondSmallestLoop();
}
}
In my opinion, it is better to have a condition to stop your scanner. So I would suggest to use a do-while instead. You also should use System.out.println, because it's ready to print in your console. You don't have to instantiate a PrintStream everytime. And by the way, your code is working, but it would be interesting to consider the thoughts we gave to you.
Your problem is not defined stop point for the while loop.
in.hasNextInt() mean: If you input an integer, it will be continue. To stop it, you can input a character that isn't an integer.
Hope to helpful

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.

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