before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.
Related
I'm so stuck of how to get the answer below, this question required to use the ArrayList and recursion as well. Code below is what I've got so far, and now I'm so stuck. I've done a lot of research but still not find the answer. If you can, you can explain and provide some answer, THANK YOU.
The elements of your array are: 1 2 3 4 5 6 -1
The multiplication of {1, 2, 3, 4, 5, 6} is 720.
Also, if the user enters the negative number, the ArrayList won't multiply that number. Please help.
public class Arraylist{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("The elements of your array are: ");
int num = scan.nextInt();
ArrayList<Integer> element = new ArrayList<Integer>();
while (true){
element.add(scan.nextInt());
}
}
}
Considering negative value terminate loop
Scanner scan = new Scanner(System.in);
System.out.print("The elements of your array are: ");
ArrayList<Integer> element = new ArrayList<Integer>();
int ans = 1;
while (true){
int num = scan.nextInt();
if(num < 0)
break;
element.add(num);
ans *= num;
}
System.out.println(ans);
Define a recursive function to get the product.
public class Arraylist{
public static int getProduct(ArrayList<Integer> elements, int index) {
if(index == elements.size() ) return 1;
else
return (elements.get(index) > 0)?
elements.get(index): 1 *
getProduct(elements, i+1);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements:");
int num = scan.nextInt(), prod = 1;
ArrayList<Integer> elements = new ArrayList<Integer>();
System.out.println("Enter " + num + " elements:");
for(int i = 0; i < num; i++) {
elements.add(scan.nextInt());
}
prod = getProduct(elements);
System.out.println("Product is: " + prod);
}
I am creating this code where I am supposed to prompt the user for a maximum of 5 integer numbers. I should store the 5 integers in an array by asking the user to enter them until the array is full or the user exits by entering -99. Then I should print out all the values of the array and calculate the average. The problem is that when I scan and store the values it shows me a null value of 0 of the fifth number instead of the number itself and it does not count it with the sum. This is the piece of code I've been working with:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num==-99 || i==4){
for(int k=0; k<i+1; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/i);
cond = true;
}
number[i] = num;
i++;
}while(!cond);
}
This is the input : 1 2 3 4 5
Every number is on a separate line
This is the output:
run:
1
2
3
4
5
1
2
3
4
0
2.5
number[i] = num;
is what adds the number the user entered to the array. If they enter -99, it's in the correct place. If they've simply entered all 4 however, it is in the wrong place. Also, you have it so it is actually dividing by the wrong number. Something like this should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num!=-99){
number[i] = num;
i++;
}
if(num==-99 || i==5){
for(int k=0; k<i; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/(i));
cond = true;
}
}while(!cond);
}
Also, do while loops are really ugly, and you can do it much smoother with just two for loops:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] number = new int[5];
double sum = 0;
int num=0,i;
for(i=0;i<5&&num!=-99;i++){
num = scan.nextInt();
number[i] = num;
}
for(int k=0;k<i;k++){
System.out.println(number[k]);
sum+=number[k];
}
System.out.println(sum/(i+1));
}
I'm trying to get both, the largest number and the largest occurring number, from a user input. The problem with my code is it only returns the first value of the array.
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
int num = input.nextInt();
int array[] = new int[num];
//loop through array
int max = array[0];
int count = 1;
for (int i = 0; i < array.length; i++) {
array[i] = num;
if(array[i] > max) {
max = array[i];
count = 1;
} else if(array[i] == max) {
count++;
}
}
//output results
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}}
I know this post is old, but Wyatt Lowery's solution is incorrect, just in case someones stumbles upon it from Google just like I did. You cannot count the number of max values in an array in the same loop like that until you have found the max value.
Example using Wyatt's class: 2 is obviously an incorrect answer.
Enter numbers:
1, 2, 3, 4, 5, 5, 7
The largest number is 7
The occurrence count of the largest number is 2
I would do:
int max = array[0];
int sum = 0;
for(int i = 1; i < array.length; i++) {
if(array[i] > max) max = array[i];
}
for(int i = 0; i < array.length; i++) {
if(array[i]==max) sum++;
}
One problem I noticed:
int num = input.nextInt();
When you do this, it is only going to take the first int (Meaning, only 1 number) As well when you are creating your array int array[] = new int[num], you are creating an array with the SIZE of num, and not actually creating an array with the VALUES of num. (Even though num is only a single number) To actually create an array of numbers, do something like this:
System.out.pritnln("Enter in numbers:");
String[] array = input.nextLine().split(", ");
An example input would be: "13, 12, 14, 14". Then the contents of the array would be those terms (And would remove spaces & commas). Your program should look something like this when finished:
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
String[] array = input.nextLine().split(", ");
//Loop through array
int max = Integer.parseInt(array[0]);
int count = 0;
for (int i = 0; i < array.length; i++) {
if(Integer.parseInt(array[i]) > max) {
max = Integer.parseInt(array[i]);
} else if(Integer.parseInt(array[i]) == max) {
count++;
}
}
//Output
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}
}
Hope this helped :-)
Think more carefully about each step you need to take.
Do you know how many numbers will be entered by the user?
Right now you are only taking in one number because you are not looping on the input
int num = input.nextInt();
int array[] = new int[num];
Here, you are creating an array the size of whatever number the user entered. This is a correct approach, more typical of C, if the user will tell you "I will enter 10 numbers" and then enters the 10 numbers. This is convenient because you will know to loop 10 times, and you will need to count a maximum of 10 different numbers.
If we don't know how many numbers will be entered you will need to loop until EOF.. something like
while(input.hasNext()) {
int currentInt = input.next();
...
}
Now you have to consider how you will be counting these items.
I hope this gives you some things to think about towards your solution..
Ok, i got this working while loop that lets the user insert random numbers, if the number is 0 or if the loops length has been achieved then it will stop, now i have to output all the numbers that was inputed and the amount of the inputs (example 1, 2, 3 amount = 3). How do i output the array? i only get 0 from the println.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0 || a1[i] == a1.length){
break;
}else{
tal += a1[i];
}
}//End of while
System.out.println("The inserted numbers are are: " + a1[i]);
}//
First of all, store tal in array and increment i every time you store. Finally iterate through array to print elements entered
import java.util.Scanner;
public class Tset {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0||i>=100){
break;
}else{
a1[i]=tal;
i++;
}
}//End of while
System.out.println("The inserted numbers are are: ");
for(int j=0;j<i;j++){
System.out.println(a1[j]+"\t");
}
System.out.println("amount is: " +i);
}//
}
Use an ArrayList instead of an array to collect the number input and then iterate over it to print them use its built-in lenght method to output the amount
I am not sure what you are trying to do, but this might help.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a1 = new int[100];
int i = 0;
int tal = 0;
int tmp;
do {
System.out.println("Insert number (0-end):");
tmp = scan.nextInt();
a1[i] = tmp;
tal += a1[i++];
} while (tmp != 0 && i < a1.length);
System.out.println("The inserted numbers are : ");
for (int j = 0; j < i-1; j++) {
if (j == i-2) {
System.out.print(a1[j] + ".");
} else {
System.out.print(a1[j] + ", ");
}
}
System.out.println("The sum is : " + tal);
}
Couple of issues:
You may want to put element you read into array like a1[i] = scan.nextInt(); and initializing tal as 0 and using a1[i] in if condition instead of tal.
You are not incrementing value of i and end's up overwriting the previous value.
Once you come out of loop, you just print 0th value of array which i think you entered 0 and came out of loop.
You can over come these as below:
Just after tal += a1[i]; increment value of i as:
i++;
Now to print your element, use a loop like:
System.out.print("The inserted numbers are are:");
for (int j=0; j<i; j++) {
System.out.print(" " + a1[j]);
}
System.out.println();
A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented