I just started learning Java and I need help on how to modify the program so that the array size is taken as a user input while using a while loop to validate the input so that invalid integers are rejected.
Also, using a while loop, take keyboard inputs and assign values to each array position.
I would appreciate any help!
Here is the code:
double salaries[]=new double[3];
salaries[0] = 80000.0;
salaries[1] = 100000.0;
salaries[2] = 70000.0;
int i = 0;
while (i < 3) {
System.out.println("Salary at element " + i + " is $" + salaries[i]);
i = i + 1;
}
It is very simple to use the while loop and take input from user Please refer below code you will understand how to take input from user and how while loop works. put all code in your main() function and import the import java.util.Scanner; and execute it and do modification to understand code.
Scanner sc= new Scanner (System.in); // this will help to initialize the key board input
System.out.println("Enter the array element");
int N;
N= sc.nextInt(); // take the keyboard input from user
System.out.println("Enter the "+ N + " array element ");
int i =0;
double salaries[]=new double[N]; // take the array lenght as the user wanted to enter
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salaries[i]=sc.nextDouble();
i++; // increment value of i so that it will store in next array element
}
you can use Scanner class for taking input from user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=sc.nextInt();
double salaries[]=new double[n];
for(int i=0;i<n;i++)
{
salaries[i]=sc.nextDouble();
}
You can also achieve using for loop and use Scanner class which is used to take input from keybord.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter the length of array you want");
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
double salaries[]=new double[length];
System.out.println("Please enter "+ length+" values");
for(int i=0;i<length; i++){
scanner = new Scanner(System.in);
salaries[i] = scanner.nextDouble();
}
scanner.close();
}
}
On java if you specific he array size, you can not change it,so you need to know array size before adding any value, but you can you use on of the List implementation like ArrayList to be able to add values without caring about the array size.
Example :
List<Double> salarie = new ArrayList<Double>();
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salarie.add(sc.nextDouble());
i++; // increment value of i so that it will store in next array
}
please read these articles for more details : difference-between-array-vs-arraylist
distinction-between-the-capacity-of-an-array-list-and-the-size-of-an-array
Related
I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}
This is just some homework but I cannot find a way to achieve it like I want. Have a look at my code please.
Once the numbers are typed, I'd just like to play around with them.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//user says if he'd like to use 3 numbers for instance (2,4,5)
System.out.println("How many numbers would you like to use? : ");
int amountOfNumbers = sc.nextInt();
System.out.println("Great! Please type in your numbers: ");
int numbers =sc.nextInt(amountOfNumbers);
// should let him write the amount of numbers he entered
}
Once he has typed the amount of numbers he'd like to use, I would like the scanner to give him the possibility to type in all of those numbers.
Let's say he the amount of numbers he'd like to use is three.
I would like him to be able to type it in the console like this:
First number + enter key
Second number + enter key
Third number + enter key
Not able to write anymore
That is what I meant here by adding "amountOfNumbers" in the scanner itself... (which is not working)
int numbers =sc.nextInt(amountOfNumbers);
BR
Consider a for loop:
for(int i = 0; i < amountofNumbers; i++){
// add to a collection / array / list
}
And then access what you need from there.
import java.util.*;
class EnterNumber{
public void enter_list_function(){
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers would you like to use?");
//Enter the Numbers of amount
int input = sc.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Great! Please type in your numbers: ");
//Input - Numbers of amount
for(int j =1; j<=input; j++ ){
int addval = sc.nextInt();
//Add the enter amount in array
list.add(addval);
}
Iterator itr=list.iterator();
while(itr.hasNext()){
//get the enter amount from list
System.out.println(itr.next());
}
}
public static void main(String[] args){
EnterNumber EnterNumber = new EnterNumber();
EnterNumber.enter_list_function();
}
}
I need to have three arrays. The first array will allow the user to enter the points scored by a basketball team of 10 players for game 1. The second array will allow the user to enter the points scored for game 2. The third array will add the first two arrays together.
I'm stuck on the first part. I don't understand how to get the user to enter a number. I tried an input, but I got an error. How do I make it so the user can enter a number?
import java.util.Scanner;
public class array2 {
public static void main(String[] args) {
int i;
int [] game1 = new int[10];
// Enter Points scored by players in game 1
// Enter points scored by players in game 2
// Add arrays together
Scanner scanLine = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
for (i=0;i<game1.length;i++)
{
System.out.println ("The score of game 1 is " + game1[i]);
}
}
}
You can get points scored by a basketball team of 10 players for game1 array in following way...
Scanner scanner = new Scanner(System.in);
int[] game1 = new int[10];
for (int i = 0; i < 10; i++) {
game1[i] = scanner.nextInt();
}
scanner.close();
After doing this, you can print the array so that you can verify that you have got correct input from the user while you are developing the feature...
for (int i = 0; i < 10; i++) {
System.out.println(game1[i]);
}
And after that, you can get points scored by a team of 10 players for game-2 and game-3 in game2 and game3 arrays respectively...
Firstly, you only need one Scanner - you can use it as many times as you like.
At the point in your code where you need to read something, set a variable equal to
scanLine.nextLine()
Or
scanLine.nextInt()
You'll probably want to do some input validation on what you've scanner to make sure it is what you're expecting
The Java API documents for Scanner should be quite helpful for understanding how to use a scanner.
If points scored is integer type, try use nextInt() to read one integer:
Scanner scanner = new Scanner(System.in)
int number = scanner.nextInt();
Then you can save your input in array:
game1[0] = number;
For fill array you can use for loop:
for(i=0; i < game1.length; i++){
game1[i] = scanner.nextInt();
}
I don't have any code to show what I am trying to do, because I honestly have no idea how to approach this.
What I am trying to do is have the user input how many numbers will be into an array. So basically, this is what I would like to be the output:
How many students in the class? 3
Enter the marks:
76
68
83
The class average is 75.67 %
I can program everything else, except for the first line. I have no idea how to read in a number into an array, so that the array will be as big as that number.
Thank you.
To start you will need to set up your scanner to read console input:
Scanner scanner = new Scanner(System.in);
You can then use function such as scanner.next() or scanner.nextInt() to get the input from the console. Hopefully this gives you some idea of where to start. If you need to look up more Scanner functions check the Scanner Documentation
As far as arrays go you simply need to save the first int input to the console and use this for size:
int size = Integer.parseInt(scanner.next());
int[] array = new int[size];
Then you should be able to use a loop to save each individual score.
import java.util.Scanner;
public class TestArrayInputViaConsole {
public static void main(String args[]) {
double sum = 0;
double avg = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many students are in the class? ");
int ArraySize = sc.nextInt();
int[] marks = new int[ArraySize];
System.out.println("Enter the marks:");
for(int i = 0; i < ArraySize; i++) {
marks[i] = sc.nextInt();
sum = sum + marks[i];
}
avg = (sum / ArraySize);
System.out.println("Average of the class : " + avg);
}
}
Details of my Homework
Topic: Single Dimensional Array
Write a java program that first read in the size of a one dimensional array, read in each array element of double type, reverses the order of this one-dimensional array.
Do not create another array to hold the result.
Hint: Use the code in the text for exchanging two elements.
Sample Output:
Please input the size of array: 4
Please input 4 double numbers: 1.0, 2.0, 3.0, 4.0
After reverse order: 4.0, 3.0, 2.0, 1.0
I have 2 problems with my assignment. Wondering if anyone can help me find a solution.
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
I need to reverse the order of the values inside the array WITHOUT
using a 2nd array.
This is my code so far.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
while (sc.hasNext()) { //Another Failed Attempt to collect the input from a single line
if (sc.hasNextDouble()) {
myArray[j] = sc.nextDouble(); //Insert user input into array
j++;
}
}
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
My problem is that when the input for the doubles is given by the user the console moves to the next line still expecting input, if input is given ArrayIndexOutOfBounds is thrown
You misunderstood something here.
In Collections.reverse(Arrays.asList(myArray)); you use Arrays.asList(myArray) that is returning a new List. Afterwards you reverse it, but you don't assign it to a variable and you just lose it.
That's not how you need to do it.
You need to think of another way of doing it.
I'll give you a hint: use the hint in the question!
and if you say you just need to reverse it, why do you need to sort it?!
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
If I understand this correctly first you need to read entire line and then parse it to read all double values from it. To read entire line of doubles from user you can invoke nextLine from scanner which handles System.in stream. Then you can either
split line on spaces and use Double.parseDouble(String) (to get double from String) on each String element from result array
wrap this line with another Scanner and use its nextDouble.
BTW if you want to read next line after nextDouble (or nextInt or nextAnythingExceptLine) you need to consume reminded line separators with another nextLine method (more info here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods).
So first part of your assignment can look like
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt();
sc.nextLine();//consume line separator to let `nextLine` read actuall next line
double[] myArray = new double[arraySize];
System.out.print("Please input " + arraySize
+ " double numbers in one line: ");
String line = sc.nextLine();
System.out.println("your numbers are "+line);
Scanner lineScanner = new Scanner(line);
int j = 0;
while (lineScanner.hasNextDouble()) {
myArray[j++] = lineScanner.nextDouble();
}
lineScanner.close();
Your second problem is that generics don't support primitive types so T in asList(T..) can be only object type. Unfortunately autoboxing works only on primitive types, so double[] can't be promoted to Double[] because every array is already an object (even arrays of primitive types).
This means that result of Arrays.asList(T.. data) for argument myArray of type double[] will not return List<double> or List<Double> but List<double[]> — a list which holds one object, the passed array, not the elements of this array. That is why reversing doesn't work for you (reversing list containing one element changes nothing, as you can't reorder list with only one element).
To solve this problem simply change type of myArray form double[] (array of primitive types) to Double[] (array of object types), to let generic type T from asList(T..) represent non-primitive Double (otherwise T can only be inferred as non-primitive double[] type).
So change your line
double[] myArray = new double[arraySize]; // Create array[userInput]
to
Double[] myArray = new Double[arraySize]; // Create array[userInput]
Probably you have to instantiate a new Scanner after you have read the array size.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
sc.close();
sc = new Scanner(System.in).useDelimiter(",");
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
First of all: Arrays.asList get Object varargs and if you pass primitive array you'll get list of primitive arrays.
Second moment: Arrays.asList returns list. And if you changed it list your original array(from which you create list) will not be changed.
You shall make collection instead array and reverse it.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
List<Double> myList = new ArrayList<Double>();
for (int i = 0; i < arraySize;) {
if (sc.hasNextDouble()) {
myList.add(sc.nextDouble());
i++;
}
}
Collections.reverse(myList);//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myList.get(i));
Use this to reverse your array.
You need to get half of the array's length to get the full reverse of the array
for(double i = 0; i < Array.length / 2; i++)
{
int x = Array[i];
Array[i] = Array[Array.length - i - 1];
Array[Array.length - i - 1] = x;
}
package display.pkg1;
import java.util.Scanner;
public class Display1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the size of array ");
int size = input.nextInt();
System.out.println(" Enter array Elements ");
double []lol = new double [size];
for(int i =0 ; i<size ; i++)
{
lol[i] = input.nextDouble();
}
for(int i =size-1 ; i>=0 ; i--)
{
System.out.println(" Array element " + ( i +1) + " is " + lol[i]);
}
}
}
Try this code
import java.util.Scanner;
public class ReverseArray{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
for(int i = 0; i < myArray.length; i++){
if (sc.hasNextDouble()) {
myArray[i] = sc.nextDouble(); //Insert user input into array
}
}
// Reverse myArray
for(int i = 0, j = myArray.length-1; i < (myArray.length/2); i++, j--){
Double temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
//Print the reversed myArray
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
}
}