I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}
Related
I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}
package perfect;
import java.math.BigInteger;
import java.util.Scanner;
public class Perfect {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
BigInteger mul = BigInteger.valueOf(1);
for(; i.compareTo(n)< 0; i.add(BigInteger.ONE))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
sum = sum.add(i);
mul = mul.multiply(i) ;
}
}
if(sum == n)
{
System.out.println(n+ "=" +mul) ;
}
else
{
System.out.println("the given number " +n+ " is not a perfect
number");
}
}
}
as it has to print 6 = 1*2*3 i used BigInteger. but it is not showing any error but the program after taking a number from user in the console i am not getting any output.
Three problems:
BigInteger is immutable, so you should do i = i.add(BigInteger.ONE) instead
When comparing sum with n, you should do sum.equals(n) instead
Store factors into a list instead of cumulatively multiplying them back to the input
Code will look nicer if you format it
import java.math.BigInteger;
import java.util.Scanner;
import java.util.ArrayList;
public class Perfect {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
sum = sum.add(i);
factors.add(i);
}
}
if (sum.equals(n)) {
System.out.print(n + "=" + factors.get(0));
for (int idx = 1; idx < factors.size(); idx++) {
System.out.print("*" + factors.get(idx));
}
System.out.println();
} else {
System.out.println("the given number " + n + " is not a perfect number");
}
}
}
I have been programming a lottery simulation, with some help from questions I've been looking at on this site. I can't seem to get the program to display the correct number of results that I am requiring, and the two sets are not comparing correctly to say how many numbers have matched.
import java.util.Set;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 1;
private static final int MAX_NUMBER_POSSIBLE = 10;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Please choose " + INPUT_SIZE + " numbers from " + MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ", hit enter after each number.");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("Congratulations, you have won!");
} else {
System.out.println("Not a winner, better luck next time.");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nLotto numbers were : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChosen = input.nextInt();
if (numberChosen < MIN_NUMBER_POSSIBLE || numberChosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in " + MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE + " range.");
} else {
userNumbers.add(numberChosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
for (Integer randomNumber : randomNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been drawn.");
}
}
There 2 problems in your code:
1) In generateRandomNumbers you should take into account that the same random number could occur multiple times. So make sure that randomNumbers is really of INPUT_SIZE size in the end.
2) In doUserNumbersMatchRandomNumbers you iterate over randomNumbers but never use randomNumber.
You store your random numbers in a (Hash-)Set, One feature of Set as described in the API is that they do not contain duplicate values (by comparing them with their equals() method). Since the Random class may output the the same value multiple times you have less values in your Set.
The better approach for generating the random numbers would be to go with a while loop:
while (random.size() < INPUT_SIZE)
{
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
keep in mind that this could result in an endless loop. Although it is very unlikely though. At least this loop does have varying execution times.
In the below code I have taken three sets of values (i<3) in the first for loop. I am able to compute the same data using different integers, e.g. i<5, i<6. Please suggest a way where I can get the number of values that are being entered on the console and then use them as <(number of values entered/2).
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("please enter 3 birth - death pairs");
List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
// int dinoStrength=s.nextInt();
for (int i = 0; i <3; i++)
{
int num1 = s.nextInt();
int num2 = s.nextInt();
Dinosaur d = new Dinosaur(num1, num2);
dinoList.add(d);
}
//System.out.println(dinoList);
Collections.sort(dinoList);
//System.out.println(dinoList);
int maxCount = 0;
List<String> ls=new ArrayList<String>();
for (Dinosaur dino : dinoList)
{
// System.out.println("start date" + dino.getStartDate());
// System.out.println("end date"+ dino.getEndDate());
int count = 0;
for (Dinosaur dino2 : dinoList) {
if (dino2.getStartDate() <= dino.getEndDate()
&& dino2.getEndDate() >= dino.getStartDate())
count++;
}
//System.out.println(count);
if (maxCount < count) {
maxCount = count;
ls.clear();
ls.add(dino.getStartDate()+"-"+dino.getEndDate());
}
else if(maxCount==count)
{
ls.add(dino.getStartDate()+"-"+dino.getEndDate());
}
}
//System.out.println(maxCount);
//System.out.println(ls);
System.out.println("Max no of Dinos alive at the same time :"+maxCount);
}
Scanner s = new Scanner(System.in);
System.out.println("please enter 3 birth - death pairs");
List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
// int dinoStrength=s.nextInt();
while(s.hasNextInt())
{
int num1 = s.nextInt();
int num2 = s.nextInt();
if(num2 ==num1)//Your condition(Here I assume date of birth should not be equal to death date.)
break;
Dinosaur d = new Dinosaur(num1, num2);
dinoList.add(d);
}
You can try something like this .
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.