I have a program that generates a list of numbers and computes all into a total and separates them into three different list. One being all of the numbers, and the other two are even and odd and then prints the even and odd array-list.
or some reason when I try to print out the two list, it only prints the first couple of numbers in the ArrayList giving my no error messages.
My Code:
import java.util.Random;
import java.util.ArrayList;
public class Projects {
public static void main(String [] args) {
Random Generate = new Random ();
ArrayList<Double> List = new ArrayList<>();
ArrayList<Double> Even = new ArrayList<>();
ArrayList<Double> Odd = new ArrayList<>();
double number;
double total = 0;
double totalEven = 0;
double totalOdd = 0;
double averageWhole;
double averageEven;
double averageOdd;
System.out.println("Generating Numbers:");
for (int Repeater = 0; Repeater < 10; Repeater++) {
number = Generate.nextInt(100);
List.add(number);
}
System.out.println("Loaded... " + "Putting Numbers Into List");
System.out.println();
for(int Insert = 0; Insert < 3; Insert++) {
System.out.println("Adding To List...");
}
System.out.println("List Completed!");
System.out.println();
System.out.println();
for (int x = 0; x < List.size(); x++) {
total += List.get(x);
//Complicated Code --- really big for loop try to simplify later.
if (List.get(x) % 2 == 0) {
Even.add(List.get(x));
}
else {
Odd.add(List.get(x));
}
}
System.out.println("Your Total Is: " + total);
System.out.println();
System.out.println();
System.out.println("Even Numbers:" + "\t" + "Odd Numbers");
for (int Output = 0; Output < Even.size() && Output < Odd.size(); Output++)
{
System.out.println(Even.get(Output) + "\t" + "\t" + Odd.get(Output));
}
averageWhole = total / List.size();
System.out.println("Average of All Numbers: " + "Average of All Even Numbers: "+ "Average of all Odd Numbers: " );
for (int averageE = 0; averageE < Even.size(); averageE++) {
totalEven = totalEven + Even.get(averageE);
}
averageEven = totalEven / Even.size();
for (int averageO = 0; averageO < Odd.size(); averageO++) {
totalOdd = totalOdd + Odd.get(averageO);
}
averageOdd = totalOdd / Odd.size();
System.out.print(averageWhole + "\t" + "\t" + "\t" + " " + averageEven + "\t" + "\t" + "\t" + "\t" + " " + averageOdd);
System.out.println();
System.out.println();
System.out.println("Command Complete...");
Sorry for it being so compacted - learning java - 2/3 weeks in -- Thanks!
When you are printing the odd and even numbers the condition in the loop will be met when the shorter list will be done, so the printing stops before printing all the numbers. You separate the printing to two separate loops.
for (int i = 0; i < Even.size(); i++) {
System.out.println(Even.get(i));
}
for (int i = 0; i < Odd.size(); i++) {
System.out.println(Odd.get(i));
}
As a side note, variables in Java should start with lowercase. Even, Odd, Output etc should be even, odd, output.
Another alternative to Guy's code that keeps the same format:
for (int Output = 0; Output < Even.size() || Output < Odd.size(); Output++) {
String even = "-";
if(Output < Even.size()){
even = Even.get(Output).toString();
}//end of if
String odd = "-";
if(Output < Odd.size()){
odd = Odd.get(Output).toString();
}
System.out.println(even + "\t" + "\t" + odd);
}
Related
I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}
When I enter my 7 integers "1 2 3 4 2 6 2" it will print the correct number of occurrences. However it will print the numbers at "49 50 51 52 53 54 55"... What in my code is missing or what do I need to change in order to get it print the correct numbers?
public static void main(String[] args)
{
final int maxEntryCount = 7;
int [][] numbers = new int [maxEntryCount][2];
System.out.print("Enter " + maxEntryCount + " integers separated by spaces: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.next().charAt(0));
}
for (int i = 0; i < maxEntryCount; i++) {
for (int j = 0; j < maxEntryCount; j++) {
if (numbers[i][0] > 0 && numbers [j][0] == numbers[i][0]) {
numbers[i][1]++;
if (j > i) {
numbers[j][0] = 0;
}
}
}
}
for (int i = 0; i < maxEntryCount; i++) {
if (numbers[i][0] > 0) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " times");
if (numbers[i][0] == 1) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " time");
}
}
}
}
Just change your loop where you are getting the user input to:
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.nextInt());
}
In your code you were reading the input as character. When you type 1 then it will take its ASCII value instead of 1.
I changed it to input.nextInt() which is used to take int as input.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());
I am having trouble with this, I need to generate an additional single random number that has the same 1-10 span. I already have the code for the random generator that produces my 20 integer array of random numbers but how do I generate a single random number in the same span within the same method. This is what I have so far and it keeps giving me random number 0: from my 20 integer array. Thanks in advance.
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1 ; i++){
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers, int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Number # " + numSearch + " was not found!");
} else {
System.out.println("Number #" + numSearch + " occurred " + count + " times.");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This loop in printNum() looks suspicious:
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
It will always print the first element of randomNumbers. It's not clear what you want, but if I had to guess it would be:
int i = RND_GEN.nextInt(randomNumbers.length);
System.out.println("Single # is: " + randomNumbers[i]);
which will print some random element of randomNumbers. Or perhaps:
int i = 1 + RND_GEN.nextInt(10);
System.out.println("Single # is: " + i);
which will print an independent random number between 1 and 10 (inclusive).
P.S. You have another one of those suspicious loops earlier in your code in createNum() as well. However, that one seems harmless in that it just assigns a second random number to randomNumbers[0].
I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}