Print out array user entered - java

i am trying to printout the number the user entered, but i got an error. Here's my code:
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int size=0,score=0;
int [] a=new int[size];
int len=a.length;
do
{
System.out.print("Please enter a number between 1 to 5: ");
size=input.nextInt();
}
while ((size<1) || (size>5));
for (int i=1;i<=size;i++)
{
do
{
System.out.print("Enter your "+i+" score (1-100):");
score=input.nextInt();
}
while((score<1) || (score>100));
}
for (int i=1;i<=size;i++)
System.out.println(a[i]+ " ");
}
}
Here's my output and the error:
Please enter a number between 1 to 5: 2
Enter your 1 score (1-100):54
Enter your 2 score (1-100):64
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Week08.BigArray2.main(BigArray2.java:27)

There are four mistakes in your code
array initialized with zero size
user input not stored in the array
iterating from index 1 but array starts with 0
Scanner not closed
Scanner input = new Scanner(System.in);
int size = 0, score = 0;
do {
System.out.print("Please enter a number between 1 to 5: ");
size = input.nextInt();
} while ((size < 1) || (size > 5));
int[] a = new int[size]; //1
for (int i = 0; i < size; i++) {
do {
System.out.print("Enter your " + (i + 1) + " score (1-100):");
score = input.nextInt();
a[i] = score; //2
} while ((score < 1) || (score > 100));
}
for (int i = 0; i < size; i++) //3
System.out.print(a[i] + " ");
input.close(); //4
output
Please enter a number between 1 to 5: 4
Enter your 1 score (1-100):99
Enter your 2 score (1-100):98
Enter your 3 score (1-100):97
Enter your 4 score (1-100):96
99 98 97 96

Few issues with you code:
Array declared with zero size. In java, size of array is declared at the time of initialization and it can altered later.
You never stored score into an array. Hence array was empty.
Always start loop index with zero in java while iterating array.
Here it is the modified working program:
import java.util.Scanner;
public class ArrayPrint {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size = 0, score = 0;
int[] a;
do {
System.out.print("Please enter a number between 1 to 5: ");
size = input.nextInt();
} while ((size < 1) || (size > 5));
//Allocating space to array
a = new int[size];
int len = a.length;
for (int i = 0; i <size; i++) {
do {
System.out.print("Enter your " + i + " score (1-100):");
score = input.nextInt();
a[i] = score;
} while ((score < 1) || (score > 100));
}
for (int i = 0; i <size; i++)
System.out.println(a[i] + " ");
}
}
Output
Please enter a number between 1 to 5: 2
Enter your 0 score (1-100):22
Enter your 1 score (1-100):11
22
11

Please have a look at your 4th line of code int [] a=new int[size];, size=0 at this time and you have initialized the integer array "a" with size 0 but you are trying to iterate array "a" at last with code for (int i=1;i<=size;i++)
System.out.println(a[i]+ " ");
} which is causing the array index out of bound exception.
Move below lines of code after first do while loop-:
int[] a = new int[size];
int len = a.length;
And now correct your last for loop as below-:
for (int i = 0; i < size; i++)
System.out.println(a[i] + " ");
}
Index of array starts at 0 and ends at size-1.

Related

How do take an user's input to make a two-dimensional array?

I am trying to make a two-dimensional array using the inputs from the user. However, the variables in my code are fixed. Thus, when a user inputs an integer x, the two-dimensional array does not have x rows and columns. How can I fix my code?
This is what I have so far:
Scanner s = new Scanner ();
int size = s.nextInt();
int a1 = new int [size];
int a2 = new int [size];
int a3 = new int [size];
for (int i = 0; i<= size; i++) {
int value = (int)(Math.random()*1);
a1[i] = value;
int value = (int)(Math.random()*1);
a2[i] = value;
int value = (int)(Math.random()*1);
a3[i] = value;
System.out.print(a1[i] + " " + a2[i] + " " + a3[i]);
The output should instead look like the following:
Enter the size of the array: 3
0 1 0
1 0 1
0 1 1
I appreciate any help or suggestions!
Here:
System.out.print("Enter the size of the array: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int twoD[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
twoD[i][j] = (int) (Math.random() * 2);
}
}
for (int[] x : twoD) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
Output:
Enter the size of the array: 4
1 0 0 0
1 0 0 1
0 1 0 0
1 0 1 1
I assume you want to do this:
System.out.println("Please enter two-dimentional array size:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Random rand = new Random();;
int[][] array = new int[n][n];
for (int[] i : array) {
for (int j : i) {
j = rand.nextInt(2);
System.out.print(j + " ");
}
System.out.println("\n");

How to create array to ask user to enter a certain amount of numbers and then take the average

Program asks the user to enter amount of numbers to average
Creates a new array of the size as amount of numbers (max)
It stores each number in an array entry
Prints the numbers entered
5 numbers on a line (use print)
Put a println appropriately (use % check)
Print the average of all the numbers
This is what i need to do but I don't think I'm starting right as I am new to java
This is what I have so far:
import java.util.Scanner;
public class AnyAverageArr {
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];
for (int i = 0; 1<= max; i++) {
arr1[i] = input.nextInt();
}
System.out.println("Average of All is " + arr1[max]);
}
}
If I'm not mistaken, this is what you need (explanation comes in comments):
try (Scanner input = new Scanner(System.in)) {
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[] arr1 = new int[max];
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
}
for (int i = 1; i <= max; i++) {
System.out.print(arr1[i - 1] + " ");
if (i % 5 == 0) {
System.out.println();
}
}
System.out.println();
double sum = 0.0;
for (int i = 0; i < max; i++) {
sum += arr1[i];
}
System.out.println("Average: " + (sum / max));
} catch (Exception e) {
e.printStackTrace();
}
You should definitely read about the for loop in java. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
You should also read about what average means.
https://www.reference.com/math/average-mean-mathematics-b2fb5e4b69989ed8
Here is a simple quick fix to your code
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int sum = 0;
for (int i = 0; i< max; i++) {
sum += input.nextInt();
}
System.out.println("Average of All is " + sum / max);
You first need to save all the elements in an array.
Then you need to calculate the sum.
Divide the sum with the total number of elements.
Here is a fix for your code:
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int numberOfElements = input.nextInt();
int[] arr = new int[numberOfElements];
int sum = 0;
for (int i = 0; i< numberOfElements; i++) {
arr[i] = input.nextInt();
sum += arr[i];
}
System.out.println("Average of All is " + sum / numberOfElements);
I have used the same loop to save the elements in the array and compute the sum at the same time.
Hope this solves your problem
I understood your requirement and i updated little in your source code.
I believe below points you may follow.
User enters a max number
User want to enter numbers for avarage and that you need to store into an array.
Sum array elements and find the avarage of it.
Refer the below source code exactly what you want.
public class StackOverflow {
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];
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
}
int sum = 0;
for(int num : arr1){
sum = sum + num;
}
double avg = sum/max;
System.out.println(" Avarage : " + avg);
}
}
import java.util.Scanner;
//here is your edited code
public class AnyAverageArr {
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];
//since array starts from 0, we need to loop less than max
//i< max : so loop will terminate when we will have input equals to max numbers
for (int i = 0; i< max; i++) {
arr1[i] = input.nextInt();
}
int sum=0;
//loop again through array and calculate the sum of each number
for(int v:arr1) {
sum+=v;
}
//divide sum by total number of inputs to get the answer
System.out.println("Average of All is " + sum/max);
}
}
------------------------------------------------------------------------
You can try the following code:
public class StackOverflow {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.print("Please enter the max number: ");
int max = input.nextInt();
// Creates a new array of the size as amount of numbers (max)
int[] arr1 = new int[max];
double sum = 0.0;
// It stores each number in an array entry
for (int i = 0; i < max; i++) {
arr1[i] = input.nextInt();
sum += arr1[i];
}
// Prints the numbers entered
// 5 numbers on a line (use print)
// Put a println appropriately (use % check)
for (int i = 0; i < max; i++) {
System.out.print(arr1[i] + " ");
}
// Print the average of all the numbers
System.out.println();
System.out.println("Average of all is " + sum / max);
}
}
}

Create a java program to display multiples of a number

I'm trying to Write the main method of a Java program that has the user enter two integers, i and n. If either integer is less than 2, output “Please enter numbers above 1.” Otherwise, output the n positive multiples of i, separated by spaces.
I'm close but can't figure out how to do display the multiples.
Here's what a sample run should look like:
Enter i: 4
Enter n: 6
6 multiples of 4 are: 8 12 16 20 24 28
import java.util.*;
public class HW5Problem3 {
public static void main (String [] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
}
System.out.print(n + " multiples of " + i + " are: ");
}
}
import java.util.Scanner;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int i = 0;
int n = 0;
//It's use to verify the inputs (i and n).
do{
System.out.print("Enter i :");
i = input.nextInt();
System.out.print("\nEnter n :");
n = input.nextInt();
if(i >= 1 || n <= 1){
System.out.println("Please enter numbers above 1 \n");
}
}while(i <= 1 || n <= 1);
System.out.print(n + " multiples of " + i + " are: ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(i*(2 + counter) + " ");
}
}
You'll need to create a loop (for loop or while loop) to iterate from 2 to n+1, and multiply i by your loop variable, outputting each value inside the loop
U can use following method in that class
public static void mult(int i,int n){
int[] arr=new int[n];
int count=2;
for(int x=0;x<n;x++){
arr[x]=i*count++;
}
for(int y=0;y<arr.length;y++){
System.out.print(arr[y]+" ");
}
and now your final code looks like
import java.util.*;
public class HW5Problem3 {
private int i = 0;
private int n = 0;
public static void main(String[] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
} else {
System.out.print(n + " multiples of " + i + " are: ");
mult(i, n);
}
}
public static void mult(int i, int n) {
int[] arr = new int[n];
int count = 2;
for (int x = 0; x < n; x++) {
arr[x] = i * count++;
}
for (int y = 0; y < arr.length; y++) {
System.out.print(arr[y] + " ");
}
}
}
n is the multiplier, i is the factor, right? In programming the multiplier is the loop maximum:
System.out.print(n + " multiples of " + i + " are: ");
for (int inc=1; inc<=n; inc++) {
System.out.print(" " + i*inc);
}
This prints out: 4 8 12 16 20 24
If you really want to have this as output: 8 12 16 20 24 28 copy/paste this line:
for (int inc=2; inc<=(n+1); inc++)

Confining User Inputed Numbers Between 1 and 30

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.

Count even and odd intergers until 0 is encountered

Here is what I have to do:
"Write a segment of code that reads a sequence of integers from the keyboard until the user enters a negative number. It should then output a count of the number of even integers and the number of odd integers read (not including the final negative value in either count). Remember - 0 is an even number. For example, if the sequence is:
2
7
15
5
88
1243
104
-1
Then the output should be
Number of even integers: 3
Number of odd integers: 4
My code just keeps going even after inputting -1. I have a feeling I am missing a {somewhere or wrote the code wrong. Here is my code:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
while (oddCount>=0&&evenCount>=0){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount = evenCount + 1;
else oddCount = oddCount + 1;
while (temp>0);
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
}
}
I think using do While loop will also prevent your isses,
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
(temp % 2==0)? evenCount++:oddCount++;
}
} while (temp > 0);
Your loop will always continue because while (oddCount>=0&&evenCount>=0) will always be true in your case. Try it like this:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
boolean continue = true;
while (continue){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount++;
else
oddCount++;
}
else {
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
continue = false;
}
}
Your code reads just one integer, then stuck at this line: while (temp>0);
The code below solve your problem:
int oddCount = 0, evenCount = 0, temp;
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (true) {
temp = in.nextInt();
if (temp < 0) {
break;
} else if (temp % 2 == 0) {
evenCount = evenCount + 1;
} else {
oddCount = oddCount + 1;
}
}
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
There are a few problems here.
First, since you never decrease oddCount and evenCount, the condition oddCount>=0&&evenCount>=0 will always be true.
Second, you have an empty loop that loops endlessly, since it's condition is true and it has no body: while (temp>0);
I'd just take out the first loop, which is redundant, and use a do while loop:
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
if (temp % 2==0) {
evenCount++;
} else {
oddCount++;
}
}
} while (temp > 0);
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
Try this..
Scanner s=new Scanner(System.in);
int evenCount=0, oddCount=0;
while(true)
{
System.out.println("Enter a number");
int n=s.nextInt();
if(n<0) break;
if(n%2==0) evenCount+=n;
else oddCount+=n;
}
System.out.println("even count "+evenCount);
System.out.println("odd count "+oddCount);

Categories

Resources