I'm at a loss here.
I have this homework assignment where I have to enable the user to input 10 numbers, place them in an array, and figure out which inputted numbers are unique.
This is my workflow right now: Input number> If number has not been inputted before, store in array; if number has been inputted before, ignore> Display the numbers inputted> Display the unique numbers
ex: Inputting 1 2 3 5 1 2 4 6 would find the unique numbers and show "1 2 3 4 5 6"
So far my code looks like this:
public class HwChapter6 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] count = new int[10];
int number = 0;
int x = 0;
boolean unique = false;
int length = count.length;
System.out.println("Insert 10 single digit numbers in any order your heart desires:");
for (int i = 0; i < count.length; i++) {
count[i] = input.nextInt();
number = count[i];
for (int j = 0; j < count.length; j++) {
Thanks for the help guys.
Instead of an array of input values, put them in a Set of Integers. Sets, by definition, store only unique values. If you add 3 'foos', there will be only one 'foo' in the set.
// Add this to your top-level loop
Set<Integer> uniqueValues = new TreeSet<Integer>;
uniqueValues.add(number);
// Add this after the loop to write all unique values on one line
for (Integer value : uniqueValues) {
System.out.print(value.toString() + " ");
}
// Now end the line.
System.out.println();
Check the numbers at they are entered, then keep track of which ones are unique by marking the same positions in a second (boolean) array with true if they are unique and false otherwise.
Then, when you print out the unique values, only print the value from each position in numbers[] if that position in uniques[] contains true.
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean[] uniques = new boolean[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
uniques[i] = true;
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && i != j) {
uniques[i] = false;
}
}
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("\nThe uniqe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
if(uniques[i]) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Store all numbers in an array.
For each stored number: check if number was inserted before and save that in a boolean array.
Print all numbers that are not marked in the boolean array.
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
The fastest and most concise and efficient way is to destructively parse the array for uniques using its first number as a magic value, after all other operations on it are complete:
Scanner input = new Scanner(System.in);
int magic = 0;
int[] numbers = new int[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("The unique numbers are: ");
magic = numbers[0];
System.out.println(magic + ", ");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && j != i) {
numbers[j] = magic;
}
}
if(numbers[i] != magic) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Yes, I have two answers - this one is significantly different from the other one, and is better, though it is much more difficult for beginners to understand. Both solutions are valid, however.
Related
I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}
Okay so im trying to find the amount of numbers that are less then
the mean of the first array. Everything but the last part is working and i
cant figure it out. The code at the bottom is what im having problems with.
for example. if i enter 1 2 3 4 5. the mean is 3 and, 1 and 2 are less then 3. so the answer would be 2 numbers.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("How many integers should we analyze?" );
int num;
num=in.nextInt();
while ( num <= 2)
{
System.out.println( "Please reenter, integer must be greater than 1" );
num=in.nextInt();
}
int[] arr = new int[num];
System.out.println( "Please enter the "+ num +" integers:" );
for (int i = 0; i < arr.length; i++)
{
arr[i] = in.nextInt();
}
System.out.print("Number of integers input: " + num);
System.out.println();
double total = 0;
for( int element : arr) {
total += element;
}
System.out.print("Total: " + (int) total);
System.out.println();
double mean = 0;
if ( arr.length > 0) {
mean = total / arr.length;
}
System.out.print("Mean: " + mean );
int big = arr[0];
for (int i = 0 ; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
}
}
System.out.println();
System.out.print("Largest: " + big);
System.out.println();
///////////////////////////////////////////////////////////////////////////////////////////////
int less;
for(int i=0;i<mean;i++) {
int num2 = i;
int[] arr2 = new int[num2];
int count = 0;
while ( num2 != 0 )
{
num2/=10;
++count;
System.out.print("Numbers less than the mean: " + count);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
}
}
you could use this code below
int count = 0;
for(int i =0;i< arr.length;i++) {
if(arr[i] < mean)
count++;
}
System.out.println("numbers less than mean " + count);
what this does is it loops through all of the original integers and if one is less than the mean, the count variable goes up by 1.
You should iterate over the array and check each element if they are under the mean. If yes, then increment an integer.
int less = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < mean) {
less++;
}
}
System.out.print("Numbers less than the mean: " + less);
I am getting user input for function (smallest or largest) and for populating array. Then according to the input function i want to compare consecutive elements and find the smallest or largest number. I cannot understand why and how to fix my code.
The code runs but does not work as supposed to. The smallest and largest numbers are all wrong
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Are you trying to find the Smallest or Largest number in an array of numbers? S/L");
String functionExpected = sc.nextLine();
System.out.println("How many elements you plan to enter? ");
int lengthOfArray = sc.nextInt();
// Populating array according to input and length
int[] numbersArray = new int[lengthOfArray];
for (int i = 0; i < numbersArray.length; i++) {
System.out.println("Enter an element here: ");
numbersArray[i] = sc.nextInt();
}
// Print out array
for (int i = 0; i < numbersArray.length; i++) {
System.out.print(numbersArray[i] + " ");
}
System.out.println();
if (functionExpected.equalsIgnoreCase("L")) {
int temp = 0;
System.out.println("We are going to find the largest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[i];
break;
} else {
temp = numbersArray[j];
break;
}
}
}
System.out.println("Largest of the three numbers is : " + temp);
}
if (functionExpected.equalsIgnoreCase("S")) {
int temp = 0;
System.out.println("We are going to find the smallest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[j];
break;
} else {
temp = numbersArray[i];
break;
}
}
}
System.out.println("Smallest of the three numbers is : " + temp);
}
}
}
As pointed out by the comments the inner loops (j based) are completely unnecessary.
int temp = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if(numbersArray[i] > temp) {
temp = numbersArray[i]
}
}
Just switch the > to < in the if for smallest/largest.
The question I am working on is:
A square with the side length n is filled with numbers 1,2,3,...n2 is a magic square if the sum of elements in each row, column, and two diagonals is the same value.
Write a program that reads in a value of 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test the following 2 features:
Does each number of 1,2,...16 occur in user input? Tell the user to try again if they enter a number that they've already entered.
When the numbers are put into a square, are the sums of rows, columns, and diagonals equal to each other?
It must be done using two-dimensional array
I am having trouble with asking the user to try again if they enter a number that they have previously entered. And, numbers in 4 x 4 do not print.
What am I doing wrong? How can I fix it?
This is the code I have so far:
Scanner in = new Scanner (System.in);
int n =4;
int[][] square = new int[n][n];
int number = 0;
int num = 0;
for (int i = 0; i <16; i++){
number = num;
System.out.print ("Enter a number: ");
num = in.nextInt();
int num_2 = 0;
if (number==num || number==num_2) {
System.out.println ("Try again.");
System.out.println ("Enter a number: ");
num_2 = in.nextInt();
}
if (num > 16){
System.out.println ("Try again.");
break;
}
}
for (int i= 0; i < n; i++){
for (int j = 0; j < n; j++) {
num+=square [i][j];
System.out.print(square[i][j] + "\t");
}
}
}
}
You can try this code for 1st feature and add code for 2nd one.
int ar[][] = new int[4][4];
System.out.println("Enter Numbers");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boolean flag = false;
int num = sc.nextInt();
if (num > 16 || num < 1) {
System.out.println("Please Enter number between 1 to 16");
flag=true;
j--;
} else {
for (int k = 0; k <= i; k++) {
for (int l = 0; l <= j; l++) {
if (ar[k][l] == num) {
System.out.println("This number already inserted...Please give another");
j--;
flag = true;
}
}
}
}
if (!flag) {
ar[i][j] = num;
}
}
}
If you can't understand anything please ask.
Hope this help.
I am just starting out with arrays and can't figure out why my code is wrong. It should let the user enter 10 values and then display the sum.
Here is my code:
//This program let the user enter 10 values and sums them up
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
for (i = 0; i < myArray.length; i++) {
int sum = 0;
sum += myArray[i];
System.out.println("The sum of the values is:" + sum);
}
}
}
}
Thank you for your support
Your problem comes from your loops (they should be one after the other), and how you initialize your variable sum (it should be initialized outside the loop).
Your code should rather be something like this:
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
}
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
Or with only one loop
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
Here is the correct code for your problem:
You have enclosed summing up values inside the
input for loop
.
You should also define int sum=0; separately outside the second for loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
for (int i = 0; i < myArray.length; i++) {//open here
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
}//close here. you will input values inside this loop
int sum = 0;//if you have to initialize sum only once, if you put it inside for loop sum wil be zero after every iteration in the loop
for (int i = 0; i < myArray.length; i++) {//here you add up all values
sum += myArray[i];
System.out.println("The sum of the values is:" + sum);
}
}
Be careful, you are doing loops inside other loops.
Every thing you do in a loop is repeated as many times as the loops number.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
// Read the value from the user
for (int i = 0; i < myArray.length; i++) {
myArray[i] = input.nextInt();
}
// display values
System.out.println("The values are ");
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
// Do sum
// Sum start at 0 outside the loop and then we are going to add every number
int sum = 0;
for (i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
System.out.println("The sum of the values is:" + sum);
}
}
i want to say that you init 10 double array but you give the value with int,it can happen error and the blew the sum is also int.
I suggest it like this.
Here you have to provide exactly 10 numbers to get the sum.
System.out.println("please enter 10 values:");
double myArray[] = new double[10];
int sum = 0;
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()){
myArray[i] = input.nextInt();
System.out.println("The values are " + myArray[i]);
sum += myArray[i];
}else{
System.out.println("Not a value.");
i--;
}
input = null;
}
System.out.println("The sum of the values is:" + sum);