need scanner input for array - java

does anyone know how to set a user input for an array, I cant find the command anywhere. my array 'grades' have 20 locations. im not so sure about 'grades.length' function but I think it prompts 20 times. BUT I added a while statement to override BUT ITS TOTALLY IGNORING THE FOR STATEMENT. if I could set user input for array I could get rid of the while statement...
program has to accept grade for number of students the user inputs btw..
import java.util.Scanner;
public class gradesaverage {
public static void main(String[] args) {
int [] grades = new int [20];
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
for ( i = 1; i <= grades.length; ++i)
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
while(i <= numStudents );
}
}

Not sure what you mean, but assuming all input is correct,
int [] grades = new int [numStudents ];
Should work if you move this line after declaration and assignment of numStudents. There is no problem in java with variable length arrays.
Also note - your iterator i starts from 1, while in java arrays start from 0.
public static void main(String[] args) {
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
int [] grades = new int [numStudents]; //the size we wanted
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
//print the array - for checking out everyting is ok
System.out.println(Arrays.toString(grades));
}

Related

I'm unable to store values in array as it is showing error?

I have to take the size of the array from user input and store it
and also I tried to store values in array ac to size but when I run the program, for loop executes once after its showing an error of boundary exception
import java.util.Scanner;
public class Odd {
int size;
int a[] = new int[size];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Size of array");
size = sc.nextInt();
for (int i = 0; i < size; i++) {
System.out.println("enter " + i + "th element");
a[i] = sc.nextInt();
}
System.out.println("your array is");
for (int i = 0; i < size; i++) {
System.out.print(a[i] + " ");
}
}
}
When you write
public class Odd
{
int size;
int a[]=new int[size];
then whenever Odd is constructed, a is created to be an array with size equal to the current value of size, which is 0.
When you then write
size=sc.nextInt();
the size of a does not change to the new value of the size variable.
There are several things wrong with your code.
First, the static method main is not able to access size and a because they are instance variables. You would need to make them static or make them local variables in the main method.
Second, size is zero. You create the array without knowing what the user will enter for size. The array has a size of zero.
Third, you don't need the variable size since you don't really use it anywhere else.
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
int[] a = new int[sc.nextInt()];
for(int i=0;i<a.length;i++){
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}
Move the array initialization to inside main method as the size is required while creating array.
public class Odd {
static int size;
static int a[];
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
for(int i=0;i<size;i++)
{
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<size;i++)
{
System.out.print(a[i]+" ");
}
}
}
and here is the output
Enter Size of array
3
enter 0th element
1
enter 1th element
2
enter 2th element
3
your array is
1 2 3
When the array is created, the value of size is defaultly 0. Do this for better results:
public class Odd
{
int size;
int a[];
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
Then whatever you have to do you can do...
You don't actually need these member variables.
import java.util.Scanner;
public class SizeArray {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Size of array: ");
int size = sc.nextInt();
int a[] = new int[size];
for(int i = 0; i < size;i ++) {
System.out.print("enter "+ i +"th element: ");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i = 0; i < size; i++) {
System.out.print(a[i]+" ");
}
sc.close();
}
}
You can just put in the main function instead of modifying them after creation.
Output:
Enter Size of array: 4
enter 0th element: 1
enter 1th element: 2
enter 2th element: 3
enter 3th element: 4
your array is
1 2 3 4
BTW please write your code in more readable format.

Java Bar Chart Printing Program

here is the question:
Write an application that reads five numbers between 1 and 30. For
each number that’s read, your program should display the same number of adjacent asterisks. For
example, if your program reads the number 7, it should display *******. Display the bars of asterisks
after you read all five numbers.
here is my code:
package Assignment.Q034;
import java.util.Scanner;
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int num;
num = 1-30;
for (int i = 0; i < 5; i++)// system asks for no more than 5 numbers
{
System.out.printf("Enter a number: ");
num = input.nextInt();
}
for (int j = 0; j < num; j++)
{
System.out.printf("*");
}
System.out.println();
}
}
program IDe used: Apache Netbeans IDE 12.4
the code does not sure any error but when I run and debug it, the output shows like this:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
*****
but the output I need is:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
*
**
***
****
*****
I am new to java programming. please help me t find the solution.
You can try to break them down individually and try to incorporate an approach like this or use these ideas for your project:
import java.util.Scanner;
public class Array {
public static void main(String[] args){
Array asteriskGenerator = new Array();
int nb[]=new int[5];
Scanner input = new Scanner (System.in);
for(int i=0;i<5;i++)
{
System.out.print("Please, Enter a number between 1 - 30 ");
nb[i]=input.nextInt();
}
input.close();
asteriskGenerator.asteriskGenerator(nb);
}
void asteriskGenerator(int nb[])
{
for(int i = 0; i < nb.length; i++)
{
for(int j=1;j<=nb[i];j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
I hope this helps in what you are trying to accomplish!
You need to read in five integers, and then when you are done, do something with them. This means you need some way to store all five integers.
The obvious solution is to store them in an array.
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int[] nums = new int[5];
for (int i = 0; i < 5; i++)
{
System.out.printf("Enter a number: ");
int num = input.nextInt();
nums[i] = num;
}
}
}
Having done that you merely need to iterate over each number in the array to print the correct number of asterisks.
public class Q034_trial
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int[] nums = new int[5];
for (int i = 0; i < 5; i++)
{
System.out.printf("Enter a number: ");
int num = input.nextInt();
nums[i] = num;
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < nums[i]; j++)
System.out.printf("*");
System.out.println();
}
}
}

I get an out of bounds error for the array but i dont understand why, error at line 23

I'm new to 2D arrays and I'm trying to input a specific value in all the coordinates so i made a loop, but for some reason it just keep going until it says that its out of bounds as if the loop isn't closing.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Number of rows: ");
int rows = input.nextInt();
System.out.println("Enter Number or columns: ");
int columns = input.nextInt();
double[][] planets = new double[columns][rows];
int columns_loop = 0;
while (columns_loop <= columns) {
int rows_loop=0;
while (rows_loop<=rows) {
System.out.println("Enter Rainfall (in mm): ");
double rows_input=input.nextDouble();
planets[columns_loop][rows_loop] = rows_input;
rows_loop++;
}
columns_loop++;
}
}
}
The problems is in your loops. See comments.
while (columns_loop <= columns) { // should be < columns
int rows_loop=0;
while (rows_loop<=rows) { // should be < rows
System.out.println("Enter Rainfall (in mm): ");
double rows_input=input.nextDouble();
planets[columns_loop][rows_loop] = rows_input;
rows_loop++;
}
columns_loop++;
}
Arrays are zero based in Java.
It is a simple mistake, but when using arrays, the index is always starting at [0] so when you call you while loop simply change it to :
import java.util.Scanner; public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Number of rows: ");
int rows = input.nextInt();
System.out.println("Enter Number or columns: ");
int columns = input.nextInt();
double[][] planets = new double[columns][rows];
int columns_loop = 0;
while (columns_loop < columns) {
int rows_loop=0;
while (rows_loop < rows) {
System.out.println("Enter Rainfall (in mm): ");
double rows_input=input.nextDouble();
planets[columns_loop][rows_loop] = rows_input;
rows_loop++;
}
columns_loop++;
}
}
This should fix that error and run correctly.

Java: Declaring array with do... while

My school homework is to declare array with 100 variables.
The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.
So far I got:
public static void runTask1() {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
for (int i = 0; i < tab.length; i++);
System.out.println("Enter number for array ");
tab [] = read.nextInt();
Please help. I'm a total newbie in programming.
You should do your homework yourself ;)
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
System.out.println("Number for array idx "+idx);
try{
tab[idx] = read.nextInt();
}catch(Exception e){
System.out.println("Wrong input");
}
if(tab[idx]<0) break;
idx++;
}while(idx<100)
Not compiled, just wrote it here.
Try that
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int index = 0;
while(index < tab.length){
System.out.println("Enter number for array ");
tab[index]= read.nextInt();
if(tab[index]<1) break;
index++;
}
System.out.println(Arrays.toString(tab));
}

I need to find specific variables that the user has inputted however I don't comprehend how

Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}

Categories

Resources