This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)
-The output is:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 5
The distinct numbers are: 1 2 3 6 4
-When it should be:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
public class ch7e5{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
int[] numberArray = new int[10];
//create array for all numbers
int[] distinctArray = new int[10];
//create array for distinct numbers
int distinct = 0;
for (int i = 0; i < 10; i++)
numberArray[i] = input.nextInt();
distinctArray[0] = numberArray[0];
//first value will be distinct
for (int i = 1; i < numberArray.length; i++) {
//loop to go through remaining values in numberArray
boolean exists = false;
//create boolean
for (int j = 0; j < numberArray.length; j++) {
//loop to check if value exists already in distinctArray
if (numberArray[i] == distinctArray[j]) {
exists = true;
break;
//break out of inner loop
}
}
if (exists == false) {
//if value is unique then add it to the distinct array
distinct++;
distinctArray[distinct] = distinctArray[i];
}
}
//}
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for (int k = 0; k < distinct; k++)
System.out.print(distinctArray[k] + " ");
}
}```
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.
EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.
Here is my code:
public class Main {
public static void main(String[] args) {
int inputs = 3;
int[] numberArray = new int[inputs];
int distinct = 0;
boolean[] mirror = new boolean[inputs];
//just setting up arrays
for(int i = 0; i < numberArray.length; i++) {
//numberArray[i] = i;
mirror[i] = true;
}
numberArray[0] = 1;
//finds out what numbers are not distinct
for (int x = 0; x < numberArray.length; x++) {
for (int y = 0; y < numberArray.length; y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
if(numberArray[x] == numberArray[y] && x != y) {
System.out.println(numberArray[x] + " is not distinct");
mirror[x] = false;//if current position in array matches any other position, number is not distinct
}
}
}
//calculates how many are distinct
for(int j = 0; j < inputs; j++) {
if(mirror[j]) {distinct++;}
}
//outputs text
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for(int k = 0; k < inputs; k++){
if(mirror[k]) {System.out.print(numberArray[k] + " ");}
}
}
}
The error was here
distinct++;
distinctArray[distinct] = distinctArray[i];
1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].
A shorter way to do it would be this
int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");
Output:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
Related
So my Professor gave us an activity where we input the amount of array and its value. Then Selection sort will be implemented and will display each pass. I manage to do the input part but only managed to display the unsorted and sorted output. I've been wracking my brains on how to show the input of each pass but I always come up short. I saw a code in C/C++ but I don't know how to read the language well enough to understand the code.
This is what the expected output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
1st Pass: 5 4 2 8 10
2nd Pass: 5 4 2 8 10
3rd Pass: 2 4 5 8 10
Sorted Array Values :2 4 5 8 10
And here's my current output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
Sorted Array Values: 2 4 5 8 10
This is my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* input number of array
* display array
* 1st pass
* 2nd pass
* 3rd
* 4th
* 5th...
*/
Scanner ss = new Scanner(System.in);
int a, j, temp;
int arr[] = new int[50];
//input number of array
System.out.print("Input a number: ");
int num=ss.nextInt();
System.out.print("");
//display array
for (a = 0; a < num; a++) {
System.out.print("a[" + a + "]: ");
arr[a] = ss.nextInt();
}
//Unsorted Value
System.out.print("UnSorted Array: ");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
System.out.println();
for (a = 0; a < num; a++) {
for(j = a + 1; j < num; j++) {
if(arr[a] > arr[j]) {
temp = arr[a];
arr[a] = arr[j];
arr[j] = temp;
}
}
}
//Passes
//Sorted Value
System.out.print("Sorted Array Values :");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
}
Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}
I am new to programming. Am currently learning Java, on nested loop now, and got stuck.
So what I want to do is to write a program that takes an integer from user and
print lines, for example if user input was 4 then the result should be like:
1
1 2
1 2 3
1 2 3 4
Here is my code so far:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
System.out.println(i);
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
}
}
}
But it prints one extra line at the end, like:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
And it is hard for me to figure out why.
I guess it is my first for loop but I don't know how to fix the for loop to get the result I want.
Any help will be appreciated. Thanks!
Don't print anything from the outer loop, only new line
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output
1
1 2
1 2 3
1 2 3 4
To avoid the trailing spaces of the other answers,
rather than printing i at the start of the loop, print 1.
Then start the inner loop from 2 and print a space before each value. And print a new line after the inner loop.
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Prints:
1
1 2
1 2 3
1 2 3 4
The problem is printing a newline and i at the same time... just take care of the new line after your for loop. The inner loop can handle all the prints.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Let's us dry run it
at first you print
1
then newline
then j goes from 1 to 1 nut no newline now 2 is printed by i now newline
so result 1 2
again j goes like 1 , 2 but no newline so again 3 is printed by i then newline
so result 1 2 3
again j goes like 1 , 2, 3, but no newline so again 4 is printed by i then newline
so result 1 2 3 4
again j goes like 1 , 2, 3, 4 // this one is the extra line
My project is to show lines with cardinals, from an initial number and
then varying this number to another number entered.
It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals.
How do I add the cardinals? With if-else?
import java.util.Scanner;
public class P02Cardinais {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number inicial of cardinals: ");
int numCardinais = keyboard.nextInt();
System.out.println("Enter the number of cardinals to add: ");
int numCardinaisAdd = keyboard.nextInt();
int i;
for (i = 0; i < numCardinais; i++) {
System.out.print("#");
} System.out.print(" - " + numCardinais);
keyboard.close();
}
}
Example of the output
(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5
You need 2 loops
one for the number of lines from initial to initial+add
one for the number of # which has to be the index of first loop (limo of j is i)
for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
for (int j = 0; j<i; j++) {
System.out.print("#");
}
System.out.println(" - " + i); // new line and index
}
import java.util.Scanner;
public class DiceSimulator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
// declare diceArray
Die[] diceArray = new Die[amountOfDie];
// create a new Die for each reference
int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {
System.out.print("How many sides on die number " + (i + 1) + "" + ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;
}
int minRoll = amountOfDie;
// int[] sumArray = new int[maxRoll + 1];//to store sum
System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();
System.out.println("\nResults");
// ******** right here is where I'm having the issue.
for (int i = 0; i < numRol; i++) {
diceArray[i].roll();
// System.out.println(diceArray[i]);
int sum = 0;
for (int f = 0; f < numRol; f++) {
sum += diceArray[f].roll();
int[] sumArray = new int[maxRoll + 1];
sumArray[sum]++;
System.out.print("\t" + sum);
}
}
// for(Die d: diceArray){
// System.out.println(d);
// }
}
}
See commented line in code: // ******** right here is where I'm having the issue.
The for loop should spit out the sum of the rolls.
It just isn't spitting out the right values. I'm just curious where I went wrong? The program should ask the user how many rolls. This would go into the first for loop and the second would roll the dice that many times.
I think what you're trying to do is roll these dice a said number of times, keeping track of how often each total is reached, so you can print them at the end. Try this:
int[] sumArray = new int[maxRoll];
for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;
System.out.print("\t" + roll);
}
System.out.println("\t:\t" + sum);
sumArray[sum-1]++;
}
for (int i = 0; i < sumArray.length; i++){
System.out.printf("%d: %d Rolls\n", i+1, sumArray[i]);
}
You can see it working here. Your most basic mistakes were:
Declare your sum array before you start calculating sums.
In the inner loop, iterate over your dice, one at a time, rolling, adding to the sum, and printing.
Print your sum and increment your count after the dice have been rolled.
If you roll two six sided dice 10 times with this algorithm, you'll get:
Results
4 3 : 7
5 5 : 10
2 2 : 4
6 5 : 11
1 1 : 2
6 5 : 11
6 5 : 11
1 2 : 3
2 1 : 3
3 5 : 8
1: 0 Rolls
2: 1 Rolls
3: 2 Rolls
4: 1 Rolls
5: 0 Rolls
6: 0 Rolls
7: 1 Rolls
8: 1 Rolls
9: 0 Rolls
10: 1 Rolls
11: 3 Rolls
12: 0 Rolls
You have a line that looks like this:
diceArray[i].roll();
The problem is that diceArray is only large as the number of dice you have. But you are trying to use it with an index of the number of rolls. This could cause an ArrayOutOfBoundsException.