I need to create a program that prints 6 numbers between 1 and 42 at random where no 2 numbers are the same. The user must also insert 6 numbers. If any number is the same as the one randomly selected by the computer, the computer must print it. If not, the computer prints you are such a loser. Now, the problem is I'm not sure about how to make sure that no 2 randomly selected numbers are the same. The program should also ask for a different number if a number less than 1, greater than 42, or equal to a previous number inserted, and scan it which I am also not able to do. (user cannot enter 2 identical numbers)
import java.util.Scanner;
import java.util.Random;
public class LotoMachine {
public static void main(String[] args) {
System.out.println("Please enter 6 numbers between 1 and 42.");
Scanner scan = new Scanner(System.in);
int[] marks = new int[6];
Random ran = new Random();
int[] x = new int[6];
boolean winner = false;
for (int i = 0; i < 6; i++) {
marks[i] = scan.nextInt();
while (marks[i] > 42) {
System.out.println(marks[i] + " is out of range. Please pick a number that is less than 43.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] < 1) {
System.out.println(marks[i] + " is out of range. Please pick a number that is greater than 0.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] == marks[i] - 1) {
System.out.println("You have already chosen " + marks[i] + "Please pick a different number.");
marks[i] = scan.nextInt();
i=0;
}
}
for (int j = 0; j < 6; j++) {
x[j] = ran.nextInt(42) + 1;
for (int y = 0; y < j; y++) {
if (x[j] == x[y]) {
x[j] = ran.nextInt(42) + 1;
j = 0;
}
}
}
System.out.print("You chose");
for (int m = 0; m < 6; m++) {
System.out.print(" " + marks[m]);
}
System.out.println(" ");
System.out.print("The random numbers are");
for (int m = 0; m < 6; m++) {
System.out.print(" " + x[m]);
}
System.out.println(" ");
System.out.print("The number(s) that matched are");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (marks[i] == x[j]) {
winner = true;
System.out.print(" " + marks[i]);
}
}
}
if (winner != true) {
System.out.println("You are such a loser");
}
}
}
You can use a Set to store the values and ask for the size after the addition. Whenever you want to deal with collections of objects which should not be repeated, a Set is a good way to go, since it allows no duplication.
Something like this:
Set<Integer> numbers = new HashSet<Integer>();
random code goes here...
int size = numbers.size();
numbers.add(newValue);
if(numbers.size() == size){
number needs to be created again...
}
Basically, there are two ways to draw 6 from 42.
The first is to draw continuously until you have 6 unique numbers. Each draw has the same probabilty (1/42) to draw a particular number. Although the likelyhood of the case that you always draw the same number is low, it is not 0. So from a statistical point of view, this is not correct. In Java you could do this is
Random rand = new Random();
List<Integer> randomNumbers = Stream.generate(() -> rand.nextInt(42))
.distinct()
.limit(6)
.collect(toList());
What you actually want to have, is to draw 1 of 42, 1 of 41, 1 of 40 ... One approach to do this is to generate a list of all possible number (1..42), draw one, remove it from the list, draw another etc. In Java that would be
final List<Integer> numbers = IntStream.rangeClosed(1, 42)
.boxed()
.collect(toList());
final List<Integer> randomNumbers2 = Stream.generate(() -> rand.nextInt(numbers.size()))
.limit(6)
.map(i -> numbers.remove((int)i))
.collect(toList());
Finally reading input until you have a valid number is easily done with a do-while loop
Scanner scanner = new Scanner(System.in);
int number;
do{
number = scanner.nextInt();
} while(number < 0 && number > 42);
if(randomNumbers2.contains(number)){
System.out.println("Winner");
} else {
System.out.println("Looser");
}
Related
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;
}
I'm trying to write a part of a program that I have for an assignment. This part of the program should take 8 user inputed integers to fill however if the user inputs a digit that has already been inputed an error is displayed and the user is asked to input a different number. As of yet I haven't written the error code and second attempt part of the code because I am having issues with the checking for duplicates part. At present the out put is True no matter what I put in.
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicates = false;
// Run while not true
while (!duplicates) {
// For loop for input into array
for (int j = 0; j < maxNum; j++) {
System.out.println("Enter digit " + digCounter + ":");
arrayIn[j] = in1.nextInt();
digCounter++;
// Check for duplicates
for (int a = 0; a < maxNum; a++) {
for (int k = a + 1; k < maxNum; k++) {
if (k != a && arrayIn[k] == arrayIn[a]) {
// Quit loop if duplicate found
duplicates = true;
}
}
}
}
System.out.println(duplicates);
}
You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;
//Run while we need numbers
while (digCounter <= maxNum) {
System.out.println("Enter digit " + digCounter + ":");
int tempNumber = scanner.nextInt();
if (numbers.contains(tempNumber)) { //If number is already chosen
System.out.println("Sorry that number has already been added");
} else { //If new number
digCounter++;
numbers.add(tempNumber);
}
}
System.out.println(numbers);
Or if you HAVE to use only arrays you can do something like this:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;
// Run while we need numbers
while (digCounter <= maxNum) {
//reset duplicate
duplicate = false;
//Get user input
System.out.println("Enter digit " + digCounter + ":");
int temp = scanner.nextInt();
for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
if (temp == arrayIn[i]) { //We have found a match
duplicate = true;
break;
}
}
//Check if duplicate
if (duplicate) {
System.out.println("Sorry that number has already been added");
} else {
arrayIn[digCounter - 1] = temp;
digCounter++;
}
}
System.out.println(Arrays.toString(arrayIn));
Hope this helps!
This code will also work if you don't want to use set.
// creating the array
int[] array = new int[10];
// Taking the first number
System.out.println("Please enter your numbers: ");
array[0] = input.nextInt();
// taking other inputs
int count;
for (count = 1; count < array.length; count++) {
int num = input.nextInt();
// Scanning the array for the number
int n;
for (n = 0; n < count; n++) {
while (array[n] == num) { // This will also work if the user
// wants to give duplicate after
// duplicate
System.out.println("You have entered this number before! Add another..");
num = input.nextInt();
n = 0;
}
}
array[count] = num;
}
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);
}
}
}
I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}
I am given the function {1,2,3,4,5}. I have to receive user input on how many ordered pairs he wants, then verify if the function is valid (values for the x-coordinate have to be between 1 and 5, and an x-coordinate CAN'T be repeated). I know how to loop for and check if the value of X is between 1 and 5, however, I am having trouble checking the string for repeating elements. I wrote the conditional expression for x less than 1 and bigger than 5, but I am stumped on how to write an expression that checks for repeating elements. Can somebody help me with that please? This is what I have so far:
import java.util.Scanner;
public class Functions
{
public static void main (String args [])
{
Scanner in = new Scanner (System.in);
int []domain = new int [5];
int [] range = new int [5];
int orderedPairs = 0;
System.out.println ("Enter the number of ordered pairs please: ");
orderedPairs = in.nextInt();
while (orderedPairs < 0 || orderedPairs > 5)
{
System.out.println ("This input is invalid. Enter a number between 0 and 5 and try again:");
orderedPairs = in.nextInt ();
}
for (int i = 0; i < orderedPairs; i++)
{
System.out.println ("Enter the x-coordinate please: ");
domain [i][0] = in.nextInt();
System.out.println ("Enter the y-coordinate please: ");
range [i][0] = in.nextInt();
}
for (int i = 0; i < orderedPairs; i++)
{
System.out.println ("f(" + domain [i][0] + "): " + range [i][0]);
}
for (int i = 0; i < orderedPairs;i++)
{
if (domain [i][0] > 5 || domain [i][0] < 1)
{
function = false;
}
for (int n = i + 1; n < orderedPairs; n++)
{
if (domain[i] == domain [n] && range [n] != range [i])
{
function = false;
}
}
}
}
}
Edit :
That is all it took, apparently! :)
The simplest way to do it is this:
1) Loop over all the domains.
2) For each domain, retrieve its value. Then loop over the domains counting the number of domains whose value equals the retrieved value.
3) If that value is anything other than 1 for each domain, report an error.