Reverse numbers using java arrays - java

Hello I am new to java and am trying to do this assignment but I can't get the needed output which is the reverse order of the numbers. Can any one help me what I am missing? Thank you so much! My Code's output looks like this:
How many floating point numbers do you want to type: 5 Type in 1.
number: 5,4 Type in 2. number: 6 Type in 3. number: 7,2 Type in 4.
number: -5 Type in 5. number: 2
Given numbers in reverse order:
Assignment
Create a program that asks the user how many floating point numbers he wants to give. After this the program asks the numbers, stores them in an array and prints the contents of the array in reverse order.
Program is written to a class called ReverseNumbers.
Example output
How many floating point numbers do you want to type: 5
Type in 1. number: 5,4
Type in 2. number: 6
Type in 3. number: 7,2
Type in 4. number: -5
Type in 5. number: 2
Given numbers in reverse order:
2.0
-5.0
7.2
6.0
5.4
My code:
import java.util.Scanner;
public class apples {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double[] numbers;
System.out.print("How many floating point numbers do you want to type: ");
int size = reader.nextInt();
numbers = new double[size];
for (int i=0; i < numbers.length; i++) {
System.out.print("Type in "+(i+1)+". number:");
numbers[i-1] = reader.nextDouble();
}
System.out.println();
System.out.println("Given numbers in reverse order:");
for (int i=numbers.length-1; i <= 0; i--) {
System.out.println( numbers[i]);
}
}
}

The second for loop condition is wrong. It should be:
for (int i = numbers.length - 1; i >= 0; i--)
because i <= 0 won't be true if numbers.length - 1 is greater than 0, therefore your for loop won't run its body.
Also in the first for loop, the index of numbers are wrong. It should be:
numbers[i] = reader.nextDouble();
This is because if i = 0, then numbers[i - 1] will be numbers[-1], and that's an invalid index.

In the first loop you are using i+1 and not i++, so the value of i is never incremented. So, your
numbers[i-1] becomes numbers[-1], which should throw an error. I am astonished, now your program is even giving you an output !
Try this
for (int i=0; i < numbers.length; i++) {
System.out.print("Type in "+(i+1)+". number:");
//numbers[i-1] = reader.nextDouble();
numbers[i] = reader.nextDouble();
}
and in second loop. You are checking from last to first so i>=0 instead of i<=0
for (int i=numbers.length-1; i >= 0; i--) {
System.out.println( numbers[i]);
}

int[] numbers;
System.out.print("How many integer point numbers do you want to type: ");
int size = reader.nextInt();
numbers = new int[size];
for (int i=0; i < size; i++) {
//System.out.print("Type in "+(i+1)+". number:");
numbers[i] = reader.nextInt();
}
System.out.println();
System.out.println("Given numbers in reverse order:");
for (int i=size-1; i >= 0; i--) {
System.out.print( numbers[i]);
}

Related

The amount of items in the store Java

I'm learning programming in Java, and I found one interesting example and solved it 80%. But there is this part that I don’t know exactly how to solve. I should enter an array indefinitely until I write "0" and then that array should break that array and add the sum of the numbers (but it is necessary that the decimals of the numbers are not limited, and the final sum at the end that is printed is rounded to 2 decimals .)
At the same time, I want to delete this part "Enter the number of purchased items: " where he asks how many items I will have, but only to enter without that part and stop collecting the sum.
import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
public static void main(String args[]){
System.out.println("Enter the number of purchased items: "); // I want to enter a array without this part
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
double sum = 0;
System.out.println("Enter item prices (each separately) : ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("The total bill amount is:" +sum + "$");
}
}
Example with BigDecimal:
BigDecimal myArray[] = new BigDecimal [size];
BigDecimal sum = new BigDecimal(0);
System.out.println("Enter item prices (each separately) : ");
for(int i=0; i<size; i++){
myArray[i] = s.nextBigDecimal();
sum = sum.add(myArray[i]);
}
Use doble and System.out printf,
excample:
double myArray[] = new double [size];
double sum = 0;
System.out.println("Enter item prices (each separately) : ");
for(int i=0; i<size; i++){
myArray[i] = s.nextDouble();
sum = sum + myArray[i];
}
System.out.printf("The total bill amount is:%.2f$",sum);

How can I take multiple integer input from scanner and store each integer in separate arrays?

I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}

ForLoop/Array Issue

I am having a little trouble figuring out what to do when it comes down to this project (generally the same for all my projects). I just want to know if I'm headed in the right direction also, I am not sure how to store the float number in the int double array. Thanks
Question & SampleOutput
Write a Java program that prompts the user to enter an integer. Use the integer as the  size for a new double array. Use a ​for loop to prompt the user to enter a floating point number for each element in the 
array, and store the number in the array.  Use a  second ​for loop to, calculate the average of all of the numbers and print it.  
Your  output should look something like the following: 
How many numbers will you enter: 5 
Enter a decimal value: 21.2 
Enter a decimal value: 3.7 
Enter a decimal value: 10.5 
Enter a decimal value: 2.6 
Enter a decimal value: 101.123 
The average is 27.824599999999997
My current code:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
int[][] Array = new int[numberOfTimes][];
for(int i = 0; i < Array.length; i--)
{
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i][
{
}
}
}
}
PS: My apologies for bad formatting. New to Stack.
Sir,
The major mistake you're committing is considering double as two. 'Double' is also a data type just like integers and float. So you need only a one dimensional array to store the values which are of type 'double'.
Secondly, i would suggest you to try to completing the code yourself once. If you're having issues in compiling it or getting wrong output, feel free to post the code online.
The desired result could have been achieved with only one 'for' loop, but I've provided the code 2 'for' loops only for the clarity.
Here's the code-
import java.util.Scanner;
public class AverageNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double AverageMean = 0;
double[] Array = new double[numberOfTimes];
// Doing the first loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
System.out.print("Enter a decimal value: ");
Array[i] = input.nextDouble();
}
// Doing the second loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
AverageMean = AverageMean + Array[i];
}
System.out.println("The average is " + AverageMean/5);
}
}
And the desired output will be-
How many numbers will you enter: 5
Enter a decimal value: 21.2
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is 27.824599999999997
Hope it helps..
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
float[] input = new int[numberOfTimes];
for(int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i] = value;
}
}
1) You need a double array instead of a two dimensional int array to store double.
2) Use input.nextDouble(); to take a double input.
3) for(int i = 0; i < Array.length; i--) will cause i to decrease negative which will next create ArrayIndexOutofBound exception at Array[i].
4) There are some other errors, better try the following code.
Try this:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double[] Array = new double[numberOfTimes];
double sum = 0;
double average = 0;
for (int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
double value = input.nextDouble();
Array[i] = value;
sum += value;
}
average = sum / numberOfTimes;
System.out.print("The average is: " + average);
}
}
Output:
How many numbers will you enter: 5
Enter a decimal value: 21.7
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is: 27.924599999999998

Inputing strings into an array

I'm a beginning programmer with the assignment to create a program that prompts the user to enter the number of elements that will then be stored into a String array. The second part of the assignment is to then list the array in ascending order. But I'm kind of stuck of the first part. If the user enters that there will be 3 elements after the 3rd string is entered I get an out of bounds exception. Below is the code.
import java.util.*;
public class arrays
{
public static void main(String[]arg)
{
Scanner input = new Scanner(System.in);
//Read user input.
System.out.print("How many Elements? ");
int num = input.nextInt();
String array[]= new String[num];
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i] = input.next();
}
System.out.println(array);
}
}
The array index starts at 0 so your loop should look like this:
for (int i = 0 ; i < num; i++ )
{
System.out.print("Enter element "+ (i+1) +": ");
array[i] = input.next();
}
Note that I also added +1 in the System.out.print to show "user friendly" output (e.g. "Enter element 1:" instead of "Enter element 0:" for the first element).
Another option would be to subtract 1 while accessing the array, which would allow you to keep the existing System.out.print line:
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i - 1] = input.next();
}
Although I feel that this is slightly less common practice.
Arrays in Java are numbered starting with zero, which means, your array of length 3 has this valid indices:
array[0]
array[1]
array[2]
I guess that's enough to send you on the right track ;-)
Start with i = 0 and go up to i < num, because in the example with three your array starts at 0 and goes up to 2, so it's no wonder that there's an out of bounds exception. That should fix the error.
you get the error because array index starts with 0. You should change your loop into this:
for (int i = 0 ; i < num; i++ )
change to array[i-1] = input.next();

I am creating a small program in java which asks for 5 integers to inputted by the user and put into an array

This is the code that I have attempted, I can get the 5 integers into the array but my problem is validating that input and giving an error message when it is not. If I put in the 5 integers and they are in the required range it works and when I input a number that is not in the required the range I get an error message which is what I want but if I enter a symbol or letter my program crashes.
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
You should check that the user inserts an int before assuming so (scanner.nextInt();).
You are using scanner.nextInt(); so it is expected that the text entered will be int and if you enter other then int it will throw exception
I would use scanner.nextLine() and then try to convert String into int with NumberFormatException check:
int value;
String input = scanner.nextLine();
try {
value = Integer.valueOf(input);
} catch (NumberFormatException ex) {
System.out.println("Number format exception");
continue;
}
if (value >= 0 && value <= 20)
...
If you are doing Q1 for C2 paper in DCU than its the Sum total you display at the end not the average. I was going to do add another While loop after the scanner.nextint() to test the input is a valid integer. The 3 validations would be is number an integer and is it in range and the number of integers to be entered to the array is 5. I am thinking very similar to you, its adding the extra check and where is goes in the sequence.

Categories

Resources