Determining Highest Number - java

I am writing a program where the user must input 10 numbers and the output should be the highest number on the 10 inputs. But I don't know what's the next code that I will write.
import java.util.Scanner;
public class kzz {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int a = 1;
int value ;
while (a < 11) {
System.out.print("Enter Value No." + a + ":");
value = reader.nextInt();
a++;
}
}
}
What should I do now?

You are reading the first value into value, fine. Say it was 86. Next time through the loop you are reading the second value into the same variable, thereby overwriting the first. So the 86 are gone forever.
Instead I suggest a second variable highestValueSoFar. Store into it the value read only if it is higher. Then at the end this will contain the highest of the 10 values.

Related

Generating Randoms but a few minor errors

I did look at the threads pertaining to randoms and implemented them into this assignment but I have 2 questions.
1) I need my program to generate random numbers (and print them) and count the iterations. I have counting the iterations down but I don't know why the random numbers don't print out. Does it have something to do with my guess = 0? Here's an example if I'm not clear.
Example:
Enter a number: 13
85
89
73
94
13
This took 5 tries
2) I have no clue why my program always ends up stuck at one number for the answer. The program immediately ends after entering the number 86.
import java.util.*;
public class FeelingLucky {
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
int tries = 0;
int guess = 0;
Random random = new Random(1);
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}
Random(1) uses seed in constructor which is always the same. Use just Random() - no parameter constructor.
import java.util.*;
public class FeelingLucky {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tries = 0;
int guess = 0;
Random random = new Random(); // No seed
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}
See Java random always returns the same number when I set the seed?
You've called nextInt() on the Random object only once, so you've only generated the one random number. Inside your loop you call nextInt() on the scanner, which is reading from System.in, so your program is halting and waiting for the user to input a number again each time around the loop.
If you want the user to enter a single number once, and then Random to keep generating numbers until they match, you'd need to swap which one is called inside the loop. To print the random numbers being generated, you'd need to add a print statement inside the loop that prints that current number.
while (guess != num) {
num = random.nextInt(100) + 1;
guess = sc.nextInt();
System.out.printf("you guessed: %d the number was %d%n",guess, num);
tries++;
}
This one will print out each time, and guess a new random number each time.

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.

How to print all inputs used from loop

I am trying to have an output where the entered numbers in the loop are all printed out as separate numbers. Example: Entered numbers: 10, 15, 1, 25.
Here is my code:
import java.util.Scanner;
public class SumofNumbersAbove0 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
int input;
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
input = scan.nextInt();
}
System.out.println("Entered Number: " + input);
System.out.println("The sum: " + number);
}
}
I get the sum of all the numbers correctly. But all I get for entered numbers is the final one.
Move your print of input into the loop where each value of input is actually present. Where you have it you only get the last input
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
System.out.println("Entered Number: " + input);
input = scan.nextInt();
}
System.out.println("The sum: " + number);
Issue:
In your code the two variables you have input and number (which should rather be named sum) are solving very different purpose. input is acting a transient pedestrial where the user-entered values come and land. From there the value is added into number and then come another user-entered value which lands onto the same pedestrial thereby knocking-off the previous value.
Thus when you print input at the bottom of your code, the value you find is the one which came last to the pedestrial (which in your case is some integer < 0)
Solution: What you want is to perform an operation (print) on each of the input values. You can do either of the following-
Perform the operation before losing the value. I mean print the value in the loop itself. Adding the value to number is another operation you are already doing before losing the value
Persist all the input values. Here you need to have some bigger pedestrial which can accomodate all the incoming user-entered value without knocking-off previous values. Once you have all the them you can revisit the values and operate on them. printing them could be one operation and accumulating their values in another variable number could be another.
Hope that helps

How to add multiple values with while statement?

I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources