Sum of the distincts Extended Description - java

I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.

Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}

From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.

There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}

Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124

When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);

Related

How do I make a calculator that multiplies more than two numbers?

I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}

Java: counting int values in an array

I have an array consisting of numbers from 0 to 10. For example,
1, 3, 5, 7, 5, 3, 1, 9
And I want to count the number of occurrences of each number from 0 to 10 in the array. Something like this (a simulation of the output):
number | occurrence
0 0
1 2
2 0
3 2
4 0
5 2
6 0
7 2
8 0
9 1
10 0
EDIT: This is a high school assignment: Write a program that repeatedly prompts the user to supply scores (out of 10) on a test. The program should continue to ask the user for marks until a negative value is supplied. Any values greater than ten should be ignored. Once the program has read all the scores, it should produce a table with the following headings (and automatically fill in the rest of the table):
Score # of Occurrences
The program should then calculate the mean score, rounded to one decimal place.
My code in response to this question:
public static int[] resize(int[] a) {
int[] expandedArray = new int[a.length + 1];
for (int i = 0; i < a.length; i++) {
expandedArray[i] = a[i];
}
return expandedArray;
}
public static void main (String[]args) {
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
boolean positive = true;
int count = 0;
int[] originArray = new int[0];
for (#SuppressWarnings("unused")
int i = 0; positive; i++) {
System.out.println("Enter a score: ");
int input = scan.nextInt();
System.out.println("The input is recorded: " + input);
if (input < 0) {
positive = false;
System.out.println("The input is negative.");
}else if (input > 10){
System.out.println("///INVALID///: Must be out of 10!");
} else {
System.out.println("count: " + count);
originArray = resize(originArray);
System.out.println("originArray resized");
originArray[count] = input;
System.out.println("The index = count = " + count +" would be assigned input: " + input);
for (int j = 0; j <= count; j++) {
System.out.println(j + ": " + originArray[j]);
}
count++;
System.out.println("count++: " + count);
}
}
System.out.println("Program has stopped taking inputs. Outputting results:");
System.out.println(" Score | Occurrences ");
}
If you are given the input array, following code will produce the results for you in the counts array.
int [] counts = new int[11];
for (int i = 0; i < input.length; i++) {
counts[input[i]]++;
}

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

Identifying, if there's duplicated inputted integer in Java

How am I going to identify the duplicated inputted integer like If I input 1 1 2 3 4, it will say number 1 is been duplicated
import java.util.*;
public class Haha {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] items = new int[5];
int sum;
System.out.println("Enter five integers: ");
sum = 0;
for (int counter = 0; counter < items.length; counter++) {
items[counter] = console.nextInt();
sum = sum + items[counter];
}
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in the reverse" + "order are: ");
for (int counter = items.length - 1; counter >= 0; counter--) {
System.out.print(items[counter] + " ");
}
System.out.println();
}
}
All you need is a Set :)
int[] arr = { 1, 1, 2, 3, 4,3 };
Set<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
boolean b = hs.add(arr[i]); // add returns false if the value is already present in the set
if (!b) {
System.out.println("duplicate value is : " + arr[i]);
}
}
O/P :
duplicate value is : 1
duplicate value is : 3

Arithmetic that takes three command-line arguments and output required as java Arithmetic: 3 + 2 = 5

class CommandLineArgs {
public static void main(String args[]) {
int l = args.length;
int sum = 0;
for (int j = 0; j < l; j++) {
sum = Integer.parseInt(args[j]) + sum;
}
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}
}
I tried using arguments but not able to do in using function as my required output is a=number1 and b=number2 and c=operator (+,-,/,*). Please help me in writing the program.
You need to use a case or if statement.
if(args[2].equalsIgnoreCase("+")
{
sum = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
}
else if(args[2].equalsIgnoreCase("*")
{
sum = Integer.parseInt(args[0]) * Integer.parseInt(args[1]);
}
etc...
you can use array for this
String[] arr= new String[l]; create a string array
for(int j=0;j<l ;j++){
arr[j] = args[j];// first of all store all inputs in the array
}
for(int i=0;i<arr.length;i++){
// then iterate over the array and check for the last char of array
if(arr[2].equalsIgnoreCase("+"){
sum = Integer.parseInt(arr[0]) + Integer.parseInt(arr[1]);
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}else if(args[2].equalsIgnoreCase("*")
{
code for multiplication
}
}

Categories

Resources