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]);
}
}
Related
import java.util.Scanner;
public class basic{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
for(int i=0;i<=2;i++)
float num = sc.nextFloat();
for(int i=0;i<=2;i++){
System.out.println(num[i]);
}
}
}
How can we take input from the user using loops and add all the user input and show's the output, for example, I have to take 3 user inputs (54, 6, 432), add all of them, and then show the output(432). I have tried but then I stuck.
You can use a variable (sum). You first initialize it to 0. And in the loop immediately after you get the input from the user for each value, add the input to this variable. Such a variable is sometimes referred to as an accumulator and the operation can be termed as an accumulation or reduce. If you want to store the values to display them later, you can use an array to store the values while they are being input and being summed. Also, in Java, the usual naming convention for class names is PascalCase, so consider naming it Basic:
import java.util.Scanner;
public class Basic {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
float sum = 0;
float[] array;
System.out.println("Enter the number of values: ");
int count = sc.nextInt();
array = new float[count];
for(int i=0;i< count;i++) {
System.out.println("Enter value " + i+1 + ": ");
float num = sc.nextFloat();
array[i] = num;
sum += num;
}
System.out.print("You have entered: ");
for(int i = 0; i < count;i++) {
System.out.print(array[i] + " ");
}
System.out.println("The sum of these numbers is " + sum);
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
int num[],sum=0;
num = new int[3];
for(int i=0;i<=2;i++){
num[i] = sc.nextInt();
sum=sum+num[i];
}
System.out.println(sum);
}
}
You can do this in too many ways, it depends on the case, etc.
Keep it simple solution
A simple solution could be creating a new variable sum to make the sum of everything, and just iterate the loop once:
System.out.println("Enter raduis : ");
float sum = 0; // create a new variable to make the sum later
for(int i=0; i<=2; i++) {
float num = sc.nextFloat();
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result
Keep it clean solution
If for some reason you are required to execute this logic into separated parts, you can use an array of values to collect the raduis and then, make the sum operation over the values of that array.
I suggest you use a method for that cause it will help you to uncouple the logic of asking numbers and make the sum operation very easy.
float[] askRaduis(int size) {
System.out.println("Enter raduis :");
float[] result = new float[size]; // create an array of floats
for(int i=0; i<=size; i++) { // Iterate until reaching 'size'
float num = sc.nextFloat();
result[i] = num; // save the iteration number at the array
}
return result;
}
Then, with this method, you can ask the numbers and later process the sum operation. Something like this:
float[] raduis = askRaduis(3); // Specify the amount of 'raduis' you want to ask.
float sum = 0; // create a new variable to make the sum later
for(float number : raduis ) { // this is a foreach loop it will iterate values of an array
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result
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
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);
}
}
I'm just trying to read the input integers from the user for example
2 2 1 1 1 < as a whole
In the debugger, it works places each integer but when
the resulting array is printed something like [I#19eda2c is printed.
public static void main(String[] args) {
int count=0;
int[] array = new int[10];
String input;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 10 integers: ");
while(scan.hasNextInt()){
array[count] = scan.nextInt();
count++;
}
System.out.println(array);
}
}
I understand now that it needs to be printed with a for loop or toString method
but I realized when I run the code,
the program waits for me even though the user inputs the integers
is my scanner logistics incorrect?
You need to use java.util.Arrays.toString() method for a 1D array .
or
java.util.Arrays.deepToString() for multi-dimensional arrays.
Your program is fine except that it will read 12 integers if user enters 12 numbers. Your loop needs to run from 0 to 9 to read 10 numbers and not as long as there are tokens in the input
Here is how Arrays.toString() works:
Returns a string representation of the contents of the specified
array. The string representation consists of a list of the array's
elements, enclosed in square brackets ("[]"). Adjacent elements are
separated by the characters ", " (a comma followed by a space).
Elements are converted to strings as by String.valueOf(int)
Here is how Arrays.deepToString() works:
Returns a string representation of the "deep contents" of the
specified array. If the array contains other arrays as elements, the
string representation contains their contents and so on. This method
is designed for converting multidimensional arrays to strings.
For more, read the docs: http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
You can't print the elements of the array just by System.out.println(array);. Iterate through the array and print each element in the array.
for(int index=0; index < count; index++ )
System.out.println(array[index]);
You are just printing textual representation of array object, use for loop to iterate in array and to display its content.
public static void main(String[] args) {
int count = 0;
int[] array = new int[10];
String input;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 10 integers: ");
while (scan.hasNextInt()) {
array[count] = scan.nextInt();
count++;
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
System.out.println(array); // prints value from default toString() method
// implementation (e.g. 'className + '#' + hashCode' in Java Oracle)
You should use something like
System.out.println(Arrays.toString(array));
to print values.
Better is to use List instead of array
public static void main(String[] args)
{
List<Integer> array = new ArrayList<Integer>();
String input;
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
array.add(scan.nextInt());
}
System.out.println("Count=" + array.size());
System.out.println(array);
}
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main. When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.
In main:
// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
In getAnswers():
// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
// Loop to receive input into array.
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
array2 = input.toCharArray();
}
return array2;
}
try
array2[index] = input.charAt(0);
after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.
Right now you're creating a new array2 with each input and thereby destroying any previous input with the previous array2 that you created.
If you absolutely need to create a char array, why not append the String answers into a StringBuffer object, and then when done, call toString().toCharArray() on the StringBuffer.
Myself, I'd create an ArrayList and just append the response to the ArrayList and at the end return the ArrayList.
It is not good idea to modify the method param. You can try :
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
String tmp = "";
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
tmp += input.chaAt(0); // check length is > 0 here
}
return tmp.toCharArray();
}