Unable to remove the last duplicate element in the array using Java - java

I've checked everything but still duplicate the last array for some reason.
What seems to be the problem?
In the Program, the first thing is to ask a user to input array size, then input numbers to that size.
Next, the code shall remove the duplicate number that a user inputted.
Lastly, the output will display the elements of the array without any duplicate.
Below is the program/code for the same:-
import java.util.Scanner;
public class Finals
{
private static Scanner sc;
public static void main(String[] args)
{
int tao, hayop, counter, bilang = 1, result, taonghayop;
sc = new Scanner(System.in);
System.out.print("Enter array size: ");
int userInput = sc.nextInt();
int userInput1 = userInput;
int[] userDatabase = new int[userInput];
for(counter=0;counter<userInput;++counter)
{
System.out.print("Enter array elements of index " +bilang +": ");
userDatabase[counter] = sc.nextInt();
bilang++;
}
for(tao=0;tao<userInput;++tao)
{
for(hayop=tao+1;hayop<userInput;)
{
if(userDatabase[tao] == userDatabase[hayop])
{
for(taonghayop = hayop; taonghayop<userInput;taonghayop++)
{
userDatabase[taonghayop] = userDatabase[taonghayop+1];
}
userInput = userInput-1;
}
else
hayop++;
}
}
System.out.print("The number(s) are: " + userDatabase[counter]);
for (result=0; result<=userInput1; result++)
{
if (result<userInput1)
{
System.out.print(" ");
System.out.print(userDatabase[result]);
System.out.print(",");
}
else if(result==userInput1)
{
System.out.print(" and ");
System.out.print(userDatabase[result]);
System.out.print(".");
break;
}
}
}
}

Related

Loop when incorrect input is given?

So basically I've been trying to get this small simple code to work but I'm running into the problem of making a loop. What I want to happen is basically this: User enters an Integer, if its not an integer it will display an error and ask for an Integer until and Integer is given. I'm having a difficult time setting up a loop cause I don't quite know what to do. Im pretty new and dumb so this is probably really easy but I'm kind of an idiot and suck at this but I'm learning.
Here's what I have.
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
You can use while loop for that.
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
You need to use a loop (for or while) to your code. You can do it like this.
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}

How to enter Uniquely entered values into an array

My homework question is to Create a procedure called NoDuplicates which will prompt the user to enter 7 unique integers. As the user enters the numbers, ask them to re-enter a number if it has been entered previously. Output the 7 unique numbers.
I have tried a lot of different combinations of while and for loops but nothing works
import java.util.Scanner;
public class arrayexcersisespart3num1 {
public static void main(String []arg) {
Scanner input = new Scanner(System.in);
noDuplicates(input);
}
public static void noDuplicates(Scanner input) {
boolean check = true;
int jumbo;
int[]noDuplicates = new int [7];
System.out.println("Please enter a unique Name");
for (int i = 0; i<noDuplicates.length;) {
System.out.println("Enter a number");
jumbo = input.nextInt();
while(check ==true|| i>0) {
check = false;
System.out.println("Please enter another number");
jumbo = input.nextInt();
if (jumbo==(noDuplicates[i])) {
check = true;
System.out.println("this Name has been previously added. Please choose another number");
}
}
jumbo = noDuplicates[i];
System.out.print("this Number has been previously successfully added in position ");
System.out.println(i+1);
check = false;
i++;
}
}
}
I don't understand your code, but:
final int N = 7; // Constant, used multiple times throughout the program
Scanner sc = new Scanner (System.in);
int[] noDuplicates = new int[N];
noDuplicates[0] = sc.nextInt();
for(int i=1; i<N; i++){ // Loops through the array to put numbers in
int query = sc.nextInt(); // Number to be put into the array
for(int j=0; j<i-1; j++){
if(noDuplicates[j] == query){ // If they are the same
i--;
continue; // Tells them to input a new number, skips all code ahead
}
}
noDuplicates[i] = query;
}
Try this logic of Collection.contains then add it in collection. It will ask the input from user from console and check whether data store in List or Not. Like this it will ask the value from user for 7 unique time on list used that
public void uniqueDataCheckOnConsoleOnLimitByList() {
int capacity = 7;
List<String> dataList = new ArrayList<>(capacity);
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (dataList.contains(s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
dataList.add(s);
capacity--;
}
}
}
As i did not check the requirement on Array. Please check it in case of array.
public void uniqueDataCheckOnConsoleOnLimitByArray() {
int capacity = 7;
String data[]= new String[capacity];
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (containsArray(data, s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
data[capacity-1]=s;
capacity--;
}
}
}
public boolean containsArray(String data[],String input){
for(String s:data){
if(input.equalsIgnoreCase(s))
return true;
}
return false;
}

Java - Looping through ArrayList to scan for matching value [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I'm trying to write a simple program using an ArrayList that adds values, removes values, and prints values. However, I'm having an issue with removing values that the user inputs. The user should input a designated amount of values (determined by the user) and then the program should remove those values (if there are duplicates then it should just remove the first instance of the number which is fine). It's not removing the values and in some cases removes one value. I'm a bit confused as to where my code is bugged. Here is my code for remove values:
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
And here is my full code:
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
printOptions();
int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}
private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}
private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}
arrayList.remove(i) removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
that is the bug your code
for more details refer below link
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,

NULL Array - how to link it in while loop

Basically I have to prompt a user to enter 10 string values, and then in another loop print them in ascending order, then in a final loop, print them in descending order. My array is bringing back null, obviously because I am not prompting users to enter actual information into the array object. I am really stuck on this. I know I need to somehow reference the "userStrings[]" array in my first while loop. I keep researching and keep getting integer loops questions and For loops. This has to be a while loop. I just can no figure out how to get the userStrings[] to actually fill up when the user enters the values. How do I get it linked in the loop?
public class HomeWork10
{
public static void main(String[] args)
{
String[] userStrings = new String[10];
int count = 0;
int count2 = 0;
while (count < 10)
{
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
count++;
}
while (count2 < 1)
{
System.out.println(Arrays.asList(userStrings));
count2++;
}
}
}
You are not putting the values in the String[]
Do it like this:
while (count < 10) {
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
userStrings[count] = userInput;
count++;
}
Also, declare Scanner input = new Scanner(System.in) outside your while() {...}
See below code snippet may solve your problem.
package com.suresh;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args) {
String[] userStrings = new String[10];
int count = 0;
System.out.println("\t Reading Array Elements ");
while (count < 10) {
System.out.print("\t Please enter a string value : ");
Scanner input = new Scanner(System.in);
userStrings[count] = input.next();
count++;
}
System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
System.out.println("\t ASCENDING ORDER ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
System.out.println("\t DESCENDING ORDER ");
Collections.sort(Arrays.asList(userStrings), new StringDescComparator());
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
}
static class StringAscComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
static class StringDescComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
You created the array with 'String[] userStrings = new String[10];' and inside your while loop to access it you need to do something like this 'userStrings[0] = input.next()' This says the first item in the array userStrings will be set to input.next(). I'm not great at java so I'm not sure what input.next() will do though.

Store/ Display Data Inputs from Arrays

I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.

Categories