Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.
Example:
If the user wants to input 3 numbers which are 10, 8, 1
10-8-1 = 1
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t++)
{
total = number[t] - number[t+1];
}
System.out.println("total: " + total);
Change the 2nd loop to this:
total = number[0];
for (int i=1; i<number.length; i++) {
total -= number[i];
}
You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.
Remember the number of items in the array must be equal to or larger than 2.
this line is totally wrong : total = number[t] - number[t+1]; as in the last loop
total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .
so as mentioned above the full correct answer code is :
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
total = number[0];
for (int i=1; i<number.length; i++) {
total = total - number[i];
}
System.out.println("total: " + total);
}
}
and here is image of the output:
[][1]
Here is a one liner (computation wise) using streams. Take the first element, stream the array skipping the first element and subtract the sum of the remaining.
int[] arr = { 10, 8, 3, 1 };
int sum = arr[0] - IntStream.of(arr).skip(1).sum();
System.out.println(sum);
But no matter how you do it, you have the potential for int overflow or underflow depending on the size of your values and the length of the array.
Related
I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}
I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}
I am trying to find the largest number in an array of 10 numbers. Here is my code:
public static void getNumber() {
int NumbersArray[] = new int[11];
int num1;
int num2;
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=1; i<11; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
}
scanner.close();
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
System.out.println("the largest number is " + largestNumber);
}
I found a real simple soultion to this here.
But the reason I am posting this is to find out what mistake have I made.
The first portion gets 10 numbers from the users and the second portion is my code to find the largest number.
Going off Pshemo's suggestion, keep a record of the largest int as the user is typing. This reduces the size of your method by half and makes it much simpler and more readable.
Program with 0-based indexing. So use int NumbersArray[] = new int[10] instead of int NumbersArray[] = new int[11]. When you declare the size of your array, simply put your desired size, you don't have to worry about 0 indexing or anything. For your for-loop, start at int i=0 and end at i<10.
public static void getNumber(){
int NumbersArray[] = new int[10];
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
if(no1 > largestNumber)
largestNumber = no1;
}
scanner.close();
System.out.println("The largest number is: " + largestNumber);
}
The problem is that you are iterating through the list twice (in a nested way). Let's say you have the following numbers: [5, 7, 3, 4]. As you go through the inner loop the first time you'll end up comparing numbers against 5. Only 7 is larger so largestNumber will be set to 7. Then you'll go through again, this time comparing against 7. Nothing is larger than 7, so it'll be left alone. Next you'll compare against 3. The last comparison there is 3 vs. 4, and since 4 is larger you end up setting largestNumber to 4, which is incorrect.
These lines:
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
Don't search for the largest number in the array, but simply search for any value in NumbersArray a value that is bigger than the current element. Thus largestNumber isn't the largest number in the array, but the last number in NumbersArray that is larger than the last element of NumbersArray, unless the last element of NumbersArray is the biggest element, in this case the largestNumber will be the last value in NumbersArray.
A working solution would be:
int max = Integer.MIN_VALUE;
for(int i : NumbersArray)
if(max < i)
max = i;
Though the most efficient solution would be to directly keep track of the currently largest input while reading the input.
And keep in mind that java-arrays are 0-based. This means that the first element is at NumbersArray[0], not NumbersArray[1], like in your code.
As far as I know you can use Java Math max() method to get largest number.
i.e. : dataType max(int number1, int number2), Math.max(number1, number2) gets the maximum between number 1 and 2.
So I'm trying to make a cash register program that takes in an array of integer prices and then adds them together to get the total sale price. Here's the snippet of my code that's important
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
for(int i=0; i<Prices.size(); i++)
{
int Total = Prices.get(i) + Prices.get(i+1);
}
System.out.println(Total);
My error says "Total cannot be resolved to a variable" and earlier it didn't like when i tried to make the increment in the loop i+2 instead of i++. Can someone help I have no idea how to add together these variables
Is this the right track?
for(int i=0; i<Prices.size(); i++)
{
int Total = 0;
int Total = Total + Prices.get(i);
}
No need of an array or list.
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
System.out.println();
}
System.out.println(total);
You're doing 2 things wrong here:
int Total = Prices.get(i) + Prices.get(i+1);
You're declaring Total inside the for loop. Do that outside with a default value of 0. Then you are adding the values of the current iteration and the next iteration. You just want to do Total = Total + Prices.get(i); or Total += Prices.get(i);.
Preferably, you can do it all as you get the values. There's no need for the additional list Prices:
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
//prices.add(i);//if you still want to keep the list
System.out.println();
}
while(in.hasNextInt());
System.out.println(total);
You have declared Total in a different scope than you are trying to use it. Additionally the logic in your loop is flawed for summing the prices. Try this:
int Total = 0;
for(int i=0; i<Prices.size(); i++)
{
Total = Total + Prices.get(i);
}
System.out.println(Total);
How do I solve the following problem?
Please see link here.
My code only works when the data is entered horizontally.
How would I go about changing my code in order to be able to display the sums like my 2nd example above in the link?
Here's my code:
import java.util.Scanner;
public class sums_in_loop {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String code = scanner.nextLine();
String list[] = code.split(" ");
for( int counter = 0; counter < list.length; counter++) {
int sum = 0;
System.out.println(sum + " ");
}
}
}
Judging by the URL you provided, the solution is rather straight-forward.
Ask the user how many pairs to enter
Declare an array of integers with a size of the user input from step 1
Run a loop based on the user input from step 1
Declare an array of integers with a size of 2
Run a nested loop of two to get user input for the two integers
Add the two numbers into the array from step 2
Display results
With that in mind (I assume only valid data is being used):
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("How many pairs do you want to enter? ");
int numberOfPairs = input.nextInt();
int[] sums = new int[numberOfPairs];
for (int i = 0; i < numberOfPairs; i++) {
int[] numbers = new int[2];
for (int j = 0; j < numbers.length; j++) {
// Be sure to enter two numbers with a space in between
numbers[j] = input.nextInt();
}
sums[i] = numbers[0] + numbers[1];
}
System.out.println("Answers:");
for (int sum : sums) {
System.out.print(sum + " ");
}
}
Results:
How many pairs do you want to enter? 3
100 8
15 245
1945 54
Answers:
108 260 1999