I am writing a program that asks for 5 user inputed numbers; however, I need to keep those numbers confined between 1 and 30. I am having trouble writing the while loop for this part of the program.
Here is my code:
Scanner input = new Scanner(System.in);
int numberCounter = 0; // Set scanner to 0
// Intialize numbers 1-5
int number1;
int number2;
int number3;
int number4;
int number5;
String asterisk = "*"; // Holds the string value "*"
int number = 0;
while (number < 1 || number > 30){
System.out.print("Enter the first number (between 1-30): ");
number = keyin.nextInt();
}
System.out.print("Please enter a number between 1 and 30: ");// Calls for user input
number1 = input.nextInt();// Stores user input for number 1
System.out.print("Please enter a number between 1 and 30: ");// Calls for user input
number2 = input.nextInt();// Stores user input for number 2
System.out.print("Please enter a number between 1 and 30: ");// Calls for user input
number3 = input.nextInt();// Stores user input for number 3
System.out.print("Please enter a number between 1 and 30: ");// Calls for user input
number4 = input.nextInt();// Stores user input for number 4
System.out.print("Please enter a number between 1 and 30: ");// Calls for user input
number5 = input.nextInt();// Stores user input for number 5
System.out.printf("%d ", number1);
for (int i = 1; i <= number1; i++)
System.out.print("*");
System.out.println();
System.out.printf("%d ", number2);
for (int i = 1; i <= number2; i++)
System.out.print("*");
System.out.println();
System.out.printf("%d ", number3);
for (int i = 1; i <= number3; i++)
System.out.print("*");
System.out.println();
System.out.printf("%d ", number4);
for (int i = 1; i <= number4; i++)
System.out.print("*");
System.out.println();
System.out.printf("%d ", number5);
for (int i = 1; i <= number5; i++)
System.out.print("*");
System.out.println();
}
}
Can anyone help steer my in the right direction.
Thank you.
You can avoid redundant code by keeping the nextInt() inside while loop and use a counter to track the desired number of inputs you want to read. And exit the loop when all the valid numbers are read.
Scanner input = new Scanner(System.in);
byte maxNum = 31;
byte minNum = 1;
int[] numbers = new int[5];
int number = 0;
int i = 0;
while (i<5) {
System.out.print("Enter number("+(i+1)+") between "+minNum + " and "+maxNum+ " : ");
number = input.nextInt();
if(number >=minNum && number <= maxNum){
numbers[i] = number;
i++;
}else{
System.out.println("--------Invalid Number :"+number+ " ");
}
}
System.out.print("Entered Numbers :");
for(int n : numbers){
System.out.print(n + ",");
}
Note : Code may fail, for char and out of range of inputs.
Try this:
if(Math.max(new int[]{number1,number2,number3,number4,number5}) <= 30 && Math.min(new int[]{number1,number2,number3,number4,number5}) >= 1){
...WITHIN YOUR RANGE...
}else{
}
What this does is check if the max of the set is less than or equal to 30, and the min of the set is more than or equal to 1, and then executing the code.
If your purpose of this program is to ask user to input 5 numbers between 1 and 30, I think you should write 'while' loop for each of the input task to be sure that each number is within the range and to ask user again if it's not.
Related
This question already has answers here:
Breaking out of an infinite loop after a user inputs a character
(4 answers)
Closed 5 months ago.
How do I break the loop in Java with a letter instead of a number? I want it to be "Press X to exit" .This is my code below.
System.out.println("Average Demo using do Loop");
System.out.println();
System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
do {
System.out.print("Enter number ");
input = scnr.nextInt();
sum = sum + input;
count++;
}
while (input != 1);
avg = sum / (count - 1);
System.out.println("The average of all numbers is " + avg);
System.out.println();
System.out.println();
count = 0;
input = 0;
avg = 0;
sum = 0;
System.out.println("Average Demo using a While Loop");
System.out.println();
System.out.println("Calculates an average of all numbers: Enter 'X' when finished");
// end of do...while loop
while (input != 1)
{
System.out.print("Enter number ");
input = scnr.nextInt();
sum = sum + input;
count ++;
}
avg = sum / (count - 1);
System.out.println("The average of all numbers is " + avg);
System.out.println();
//end of while loop
for (int i = 0; i < 10; i++)
{
for (int y = 0; y <= i; y++)
{
System.out.print("*");
}
System.out.println();
//end of for loop
}
You'll have to use scanner.nextLine() to get the input as a string first, as using scanner.nextInt() for character will cause an exception.
do {
System.out.print("Enter number ");
string input = scnr.nextLine();
if(input.equals("x") || input.equals("X") ) {
break;
else {
int num = Integer.parseInt(input);
sum = sum + num;
count++;
}
} while ( ! input.toUpperCase.equals("X") );
This program asks for 10 integer numbers and stores these integer numbers in an array.
The program then counts how many odd, how many even, how many negative, how many positive, and how many zero numbers. The program should also display what are the numbers that belong in these groups.
this is my program:
import java.util.Scanner;
public class count {
public static void main (String[] args)
{
int i,x,a[] = new int[10];
int n=0,p=0,e=0,o=0,z=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 Numbers");
for(i=0;i<10;i++)
{
System.out.println("Enter Number :");
a[i] = input.nextInt();
}
for(i=0;i<10;i++)
{
if(a[i]<0)
n++;
else
p++;
x=a[i]%2;
if(x==0)
e++;
else
o++;
if(a[i]==0)
z++;
}
//print
System.out.println("Total Even Numbers = "+e);
System.out.println("Even Numbers are = ");
System.out.println("Total Odd Numbers = "+o);
System.out.println("Odd Numbers are = ");
System.out.println("Total Negative Numbers = "+n);
System.out.println("Negative Numbers are = ");
System.out.println("Total Positive Numbers = "+p);
System.out.println("Positive Numbers are = ");
System.out.println("Total Zero Numbers = "+z);
}
}
This is the output of it.
Enter 10 Numbers
Enter Number :
0
Enter Number :
0
Enter Number :
2
Enter Number :
-3
Enter Number :
-4
Enter Number :
6
Enter Number :
9
Enter Number :
5
Enter Number :
0
Enter Number :
9
Total Even Numbers = 6
Even Numbers are =
Total Odd Numbers = 4
Odd Numbers are =
Total Negative Numbers = 2
Negative Numbers are =
Total Positive Numbers = 8
Positive Numbers are =
Total Zero Numbers = 3
As I said in the comments a simple solution will be to save every number to the corresponding List
List<Integer> evenNumbers = new ArrayList<>();
Then every time you check each number with the if statements instead of having a counter just add the number to the list
if (numbers[i] % 2 == 0) evenNumbers.add(numbers[i]);
And last print them as you already do but check the size of each List
System.out.println("Total Even Numbers = " + evenNumbers.size());
System.out.println("Even Numbers are = " + evenNumbers);
import java.util.Scanner;
public class countPZN {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
int p = 0, o=0;
int z = 0, e=0;
int num [] = new int[7];
System.out.println("Enter the number");
for (int i = 0; i < 7; i++) {
System.out.println("Enter the number " + (i + 1));
num[i] = input.nextInt();
}
for (int i = 0; i <7; i++) {
if (num[i] < 0)
n++;
else if(num[i]>0)
p++;
else if(num[i]==0)
z++;
else if(num[i]%2==0)
e++;
else
o++;
}
System.out.println("Number of negative number is " + n);
System.out.println("Number of positive number is " + p);
System.out.println("number of zero number is " + n);
System.out.println("number of even number is " + e );
System.out.println("number of odd number is " + o );
}
}
I am so very new to coding and forgive me if this very basic question has been answered however when searching I still cannot see what is missing from my code. I am simply trying to get the sum of 5 integers. I can get it to print the integers however it just runs after that and never gives the answer. What is it waiting for me to do or what is my code missing? I have no errors so I am just not seeing what is wrong.
System.out.print("Please enter 5 integers: ");
int arr = input.nextInt();
int sum = 0;
for(int a = 1; a <= 100; a++){
arr = input.nextInt();
}
sum = sum + arr;
System.out.println("The sum of 5 integers is: " + sum);
Try:
System.out.print("Please enter 5 integers: ");
Scanner input = new Scanner(System.in);
int sum = 0;
for(int a = 1; a <= 5; a++){
sum += input.nextInt();
}
System.out.println("The sum of 5 integers is: " + sum);
public class Ex51 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many integers as you wish. Enter 0 to stop." + "\nReturns "
+ "\nNumber of negative integers input. " + "\nNumber of positive integers input." + "\nTotal sum."
+ "\nMean.");
int i = 0;
int sum = 0;
int temp = 0;
int minusCount = 0;
int plusCount = 0;
float mean = 0;
boolean isZero = false;
do {
System.out.print("Enter an integer: ");
temp = input.nextInt();
if (temp == 0 && i == 0) {
isZero = true;
break;
} else if (temp < 0) {
minusCount++;
} else if (temp > 0)
plusCount++;
if (temp != 0) {
i++;
sum += temp;
mean = (float) sum / (float) i;
}
} while (temp != 0);
if (!isZero) {
System.out.printf("\nThe number of positives is: %d" + "\nThe number of negatives is: %d"
+ "\nThe total is: %d" + "\nThe average is: %.2f", plusCount, minusCount, sum, mean);
} else {
System.out.println("No numbers are entered except 0.");
}
}
}
And this is a sample run:
Enter as many integers as you wish. Enter 0 to stop. Returns
Number of negative integers input. Number of positive integers
input. Total sum. Mean. Enter an integer: 8 Enter
an integer: 6 Enter an integer: 20 Enter an integer: -2
Enter an integer: 0 The number of positives is: 3 The
number of negatives is: 1 The total is: 32 The average is:
8$00
My problem is right at the bottom: 8$00
When I specify %.2f for the float with no special characters in between.
The desired output would be "8.00" for arg mean.
I posted all of the code because I think I would make obvious any beginner mistakes fairly obvious and if not is there any issues with my settings.
I'm running this on Eclipse with jre9.
You are missing a number before '.' for example 2.2f.
For the rest of the code, for initializing you can do it all in one line. The last if statement is useless because you already verified in the first if it is 0, so you dont need a condition for this one. And you will not get there anyway because your while condition is that temp is not 0.
For the mean you can do:
mean = (float)(sum/i);
I think you are just complecating your life.
you could do this:
int temp = 1;
int positive = 0;
int negative = 0;
int i = 0;
int sum = 0;
while (temp != 0)
{
System.out.print("Please enter an integer:");
temp = input.nextInt();
if(temp == 0)
//your print statement here
else if(temp > 0)
positive ++;
else
negative ++;
sum += temp;
i++;
}
Sorry i'm stuck on converting this to do while loop can anybody help me please.
int sum = 0;
int num;
System.out.print("Enter number: ");
num = sc.nextInt();
// Store the user input into variable num
// Complete the for loop to start from 1
// and end at num
for (int i = 1 ; i <=num ; i++)
sum += i;
System.out.println("The sum is " + sum);
and this is my do while loop
int sum = 0;
int num;
int i = 1;
do {
sum += i;
System.out.print("Enter number: ");
num = sc.nextInt();
i++;
} while (i <= num);
System.out.println("The sum is " + sum);
int sum = 0;
int num;
int i = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
do{
sum += i;
i++;
}
while ( i <=num );
System.out.println("The sum is " + sum);
Initialize i to zero, since do-while does first before checking, as opposed to for that checks first before doing. And your do-while will work the same as your for.Or else your do-while will have a sum of 1 even if your num is 0. As opposed to your for that will have sum=0 if num is 0.
In the first case, you enter num value outside the for, the second case you do it on the do/while. So I supposed you want to do this:
//Variables
int sum = 0;
int num;
int i = 0;
//Select num
System.out.print("Enter number: ");
num = sc.nextInt();
do {
sum += i;
i++;
} while (i <=num);
System.out.println("The sum is " + sum);
First you may have to study the basics of the loops a bit more. The difference between while loop and do-while loop is the place where the condition is being checked. Do-while loop checks the condition after executing the code block. And the while loop doesn't. It checks before the execution.
int num = sc.nextInt();
int i = 1;
int sum = 0;
do{
sum += i;
i++;
}while(i <= num); //check condition after the running do block
System.out.println(sum);
**This depends on your input. That means if your input is zero the answer will be wrong. Because your i = 1 and sum becomes equals to 1.