I'm trying to make a program that will not accept duplicates from user input. If user inputs the same integer from the array, it errors or prints out the integers that were already inputted.
Scanner input = new Scanner(System.in);
int[] arr = new int[5];
int[] dup = new int[5];
int duplicate;
for ( int i = 0 ; i < arr.length; i++ )
{
System.out.println ("Enter integer: ");
arr[i] = input.nextInt();
if((arr[i] >=10) && (arr[i] <=100))
{
System.out.printf("Output: %d\t",arr[i]);
for(int j = 0 ; j < arr[i] ; j++)
{
if(dup[j] == arr[i])
{
dup[j] = arr[i];
duplicate = dup[j];
}
}
}
else
{
System.out.println ("enter number between 10-100");
}
}
I expect to get
Enter integer: 10
Output: 10
Enter integer: 20
Output: 10 20
Enter integer: 10
No duplication
Output: 10 20
You can use set to remove duplicate values and print only originals.
int Numbers[] = new int[10];
Set<Integer> set = new HashSet<>();
Scanner Number = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
Numbers[i]= Number.nextInt();
set.add(new Integer(Numbers[i]));
if(i == Numbers.length) {
break;
}
}
System.out.println("Distinct Values " + Arrays.toString(set.toArray()));
I/P == 10,10,10,10,20,20,50,30,30,30
O/P == 10,20,50,30
You can use HashSet collection to store unique elements
Scanner input = new Scanner(System.in);
HashSet<Integer> nums = new HashSet<Integer>();
int n = 5; //number of iterations
for ( int i = 0 ; i < n; i++ )
{
System.out.println ("Enter integer: ");
int num = input.nextInt();
if((num >=10) && (num <=100))
{
boolean isUnique = nums.add(num); //if number is unique returns true
if (isUnique)
System.out.printf("Output: %d\n", num);
else {
System.out.print("No duplication Output:");
for (int item: nums)
System.out.printf(" %d", item);
return 0;
}
}
else
{
System.out.println ("enter number between 10-100");
}
}
Scanner input = new Scanner(System.in);
int[] arr = new int[5];
int duplicate;
boolean isDuplicate = true;
for ( int i = 0 ; i < arr.length; i++ ) {
isDuplicate = true;
System.out.println ("Enter integer: ");
duplicate = input.nextInt();
if((duplicate >=10) && (duplicate <=100)) {
for(int j = 0 ; j < i ; j++) {
if(arr[j] == duplicate) {
isDuplicate = false;
break;
}
}
if(isDuplicate) {
arr[i] = duplicate;
}
} else {
System.out.println ("enter number between 10-100");
i--;
}
}
you can print array using "System.out.println(Arrays.toString(arr))"
I have modified your approach a bit to make you understand
package so.questions.array;
import java.util.Scanner;
public class ArrayDuplicates {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
boolean flag = false;
System.out.println("Enter integer: ");
int val = scanner.nextInt();
if (val >= 10 && val <= 100) {
for (int j = 0; j < i; j++) {
if (val == arr[j]) {
flag = true;
i--;
break;
}
}
if(!flag) {
arr[i] = val;
}
} else {
System.out.println("enter number between 10-100");
}
System.out.print("Output:");
for (int j = 0; j <= i; j++) {
System.out.printf(" %d\t", arr[j]);
}
System.out.println();
}
scanner.close();
}
}
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
int index = 0;
for(int i=0;i<arr.length;i++) {
System.out.println ("Enter integer: ");
int input = sc.nextInt();
if(input >= 10 && input<=100) {
if(index == 0) {
arr[index] = input;
index++;
}
else {
int k=index;
boolean dupExist = false;
while(k>=0) {
if(arr[k]==input) {
dupExist = true;
break;
}
k--;
}
if(!dupExist) {
arr[index] = input;
index++;
}
}
System.out.print("Output:");
for(int k=0;k<index;k++) {
System.out.print(arr[k]+" ");
}
System.out.println();
}
else {
System.out.println ("enter number between 10-100");
i--;
}
}
Without HashSet.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter integer: ");
int temp = input.nextInt();
if (isFound(temp, arr)) { // if temp is found in arr
System.out.println("No duplication");
} else {
if ((temp >= 10) && (temp <= 100)) {
arr[i] = temp;
System.out.print("Output: ");
for (int j = 0; j < arr.length; j++) {
System.out.print(" " + arr[j]);
}
System.out.println();
} else {
System.out.println("enter number between 10-100");
}
}
}
input.close();
}
private static boolean isFound(int temp, int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
return true;
}
}
return false;
}
}
Related
When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.
I'm trying to add spaces and a counter between consecutive runs in a simple java coin toss program.
I want this output: HHHHTHTTTTTTTHTTTHHHTTTTHTTHHHTTTTHHTHHHHHTTTTTTHT
to look print like this: HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1
I am not sure how to position the conditions in the loop so that spaces and a counter are printed between the consecutive 'T's and 'H's. Do I need to use a different kind of loop? I have tried rearranging the loop and using break; and continue; but haven't gotten the result to print correctly.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
for (int i=0; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
int previousFlip = 0;
int tailsCount = 0;
int headsCount = 0;
if (currentflip == 0) {
System.out.print("H");
previousFlip = 0;
headsCount++;
}
else if (currentflip == 1) {
System.out.print("T");
previousFlip = 1;
tailsCount++;
}
if (previousFlip == 0 && currentflip == 1) {
System.out.print(headsCount + " ");
headsCount = 0;
}
else if (previousFlip == 1 && currentflip == 0) {
System.out.print(tailsCount + " ");
tailsCount = 0;
}
}
}
You can just store the last flip and a counter like
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
int counter = 1;
int previousFlip = randomNum.nextInt(2);
printFlip(previousFlip);
for (int i=1; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
if (currentflip == previousFlip) {
counter++;
} else {
System.out.print(counter + " ");
counter = 1;
previousFlip = currentflip;
}
printFlip(currentflip);
}
System.out.print(counter);
}
private static void printFlip(int currentflip) {
if (currentflip == 0) {
System.out.print("H");
}
else if (currentflip == 1) {
System.out.print("T");
}
}
Via a single method:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
if (timesFlipped <= 0)
return;
Random randomNum = new Random();
boolean isHeads = false;
int sequence = 0;
for (int i = 0; i < timesFlipped; i++) {
boolean prevFlip = isHeads;
isHeads = randomNum.nextBoolean();
if (i > 0 && isHeads != prevFlip) {
System.out.print(sequence + " ");
sequence = 0;
}
sequence++;
System.out.print(isHeads ? "H" : "T");
}
System.out.println(sequence);
}
I want make like this:
input number[0][0]=201
input number[0][1]=202
input number[1][0]=203
input number[1][1]=204
input last = 203
then find if last input same with above, if true, s.o.p find, else not found
my code:
import java.util.Scanner;
public class array_input {
public static void main(String[] args) {
int a[][];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("input number[" + i + "][" + j + "]");
int b = scan.nextInt();
a[i][j] = b;
}
}
System.out.print("input what u want");
if (a[i][j] == b) {
System.out.print("found");
} else {
System.out.print("not found");
}
}
}
Maybe you mean something like this ?
import java.util.Scanner;
public class array_input
{
public static void main(String [] args){
int a [][] = new int[2][2];
Scanner scan = new Scanner(System.in);
for(int i = 0;i < 2; i++){
for(int j = 0; j < 2; j++){
System.out.printf("input number[%d][%d]=", i, j);
int b = scan.nextInt();
a[i][j]=b;
}
}
System.out.print("input last = ");
int needle = scan.nextInt();
for (int[] row : a){
for (int col : row){
if(col == needle){
System.out.println("found");
return;
}
}
}
System.out.print("not found");
}
}
Ok, I guess that this is what you want. This checks if the last input of the array is in the array (excluding the last input).
boolean valueInArray = false;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
if(a[i][j]==b && (i != 2 || j != 2)){
valueInArray = true;
}
}
}
if(valueInArray){
System.out.print("found");
} else {
System.out.print("not found");
}
I have to make an array whose 10 numbers are chosen by the user through a scanner. The program orders the 10 numbers in ascending order, then prints out the new list. Then It asks the user to enter any number and then uses a binary search to see if the number is in the list of 10 numbers.
Here is what I have so far:
import java.util.Scanner;
public class lab11 {
public static void main(String[] args){
double[] numbers = new double[10];
System.out.println("Please enter 10 double values:");
for (int i=0;i<10;i++){
numbers[i] = inputArray();
}
System.out.println("sorting");
print(selectionSort(numbers));
System.out.println("Please enter a search key:");
}
public static double inputArray(){
Scanner input = new Scanner(System.in);
System.out.print(">");
double d = input.nextInt();
return d;
}
public static double[] selectionSort(double[] list){
double temp;
for(int i=0; i < (list.length-1); i++){
for(int j = i+1; j < list.length; j++){
if(list[j] < list[i]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void print(double[] arr){
for(double d:arr){
System.out.println("list["+j+"]"+" = "+d);
}
}
public static int binarySearch(double[]list, double key){
int low=0,high=list.length -1;
key =input.nextInt();
while(high>=low){
int mid=(low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key==list[mid]) return mid;
else low=mid+1;
}
return-1;
}
}
I need help with 2 things.
(1) is under the Print method. I want the program to print out like "list[i] = d" The d a number that the user puts in and it works fine, but the i doesn't. I want it to be the array number which is 0 through 9.
(2) I need help with invoking the binary search so I can have an output for the search.
Just for the right input, you can write a do...while loop, which loops till the input is valid:
for (int i = 0; i < 10; i++) {
double number;
Scanner input = new Scanner(System.in);
do {
System.out.print(">");
number = input.nextDouble();
} while (number < 0 || number > 10);
}
}
For the output you seem to want use
// [...] perform the sorting [...]
// enter the search key
System.out.println("Please enter a search key:");
final int position = Arrays.binarySearch(numbers, input.nextDouble());
if (position < 0) {
System.out.println("key is not in the list");
} else {
System.out.println("key is at position " + position);
}
I would write like this
public static void main(String[] args) {
// initialize
double[] numbers = new double[10];
Scanner input = new Scanner(System.in);
// insert variables into array
inputArray(numbers, input);
// start sorting
System.out.println("sorting");
selectionSort(numbers);
// print the sorted array
print(numbers);
// binary search
binarySearch(numbers, input);
// close scanner
input.close();
}
public static void inputArray(double[] numbers, Scanner input) {
System.out.println("Please enter 10 double values:");
for (int i = 0; i < 10; i++) {
System.out.print(">");
numbers[i] = input.nextDouble();
}
}
public static void print(double[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println("list[" + i + "]" + " = " + numbers[i]);
}
}
public static double[] selectionSort(double[] list) {
double temp;
for (int i = 0; i < (list.length - 1); i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[i]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void binarySearch(double[] numbers, Scanner input) {
System.out.println("Please enter a search key:");
double key = input.nextDouble();
int index = Arrays.binarySearch(numbers, key);
if (index < 0) {
System.out.println(key + " is not in the list");
} else {
System.out.println(key + " is in the list, index = " + index);
}
}
I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:
public class xtree {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
Thank you, im a beginner to java so please be lenient ;)
Well, I would separate the method out into two:
A printChristmasTree method, which accepts the height as a parameter
Your main method, which just deals with taking user input and calling printChristmasTree or exiting
Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:
public static void main(String[] args) {
Scanner scan = new Scanner(in);
while (true) {
System.out.print("Please enter a number (0-40): ");
int height = scan.nextInt();
if (height == 0) {
// Exit the program
return;
} else if (height >= 1 && height <= 40) {
printChristmasTree(height);
} else {
System.out.println("Invalid input.");
}
}
}
There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.
The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.
Use a while loop:
Scanner scan = new Scanner(System.in);
System.out.print("please enter a number: ");
int temp = scan.nextInt();
while (temp>0) {
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
System.out.print(" ");
}
System.out.println("*");
temp = scan.nextInt();
}
Here's the code for doing that:
public class xtree {
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
temp = scan.nextInt();
if(temp >= 1 && temp <= 40){ //don't display a tree higher than 40
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}else if(temp != 0){
out.print("Please enter a number between 1 and 40!");
}
}while(temp != 0);
}
}