How to enter Uniquely entered values into an array - java

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;
}

Related

How to calculate the percentage of words in input strings in java

I am trying to calculate the percentage of valid inputs of words.
I'm stuck and every method I've tried doesn't work. I was starting learning java two months ago,so i am new in this and i am not shure if I have done the right code.
Could someone give me some advice on how to word it.Thanks in Advance
public class Subject3
{
public static void main (String[]args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings=0;
do {
valid = true;
System.out.print("How many strings?: ");
try{
numOfStrings = Integer.parseInt(scan.nextLine());
}catch (NumberFormatException e){
System.out.println("Not a word");
valid = false;
}
}while (!valid);
String[] stringPali = new String [numOfStrings];
String input;
for (int i=1; i<numOfStrings+1 ; i++) {
do {
valid = true;
System.out.print("Enter string no." +i );
System.out.print(":");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9]+")){
System.out.println("Not a word");
}
}while (!valid);
}
System.out.println("Results");
System.out.println("Total number of strings: "+ numOfStrings);
System.out.println("Percentage of words:" +(percentage)("%"));
System.out.println("Words starting with capital letter: "+("%"));
}
}
System.out.println("Not a word"); this meesage is wrong. it should be not a number.
You created an array stringPali but never used it? why?
loops starting with 1 is confusing. But it's up to you.
You should first add the words to the array finally you can count.
You need the full user input to calculate percentage. So no point of counting valid strings while user is still entering input. Do it at the end.
You can use regex to match the strings that only contain letters and the strings that start with a capital letter.
import java.util.Scanner;
public class ExampleCase {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("How many strings?: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Not a number");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
for (int i = 0; i < numOfStrings; i++) {
System.out.print("Enter string no." + i);
System.out.print(":");
String input = scan.nextLine();
stringPali[i] = input;
}
System.out.println("Results");
System.out.println("Total number of strings: " + numOfStrings);
int validStringCount = countStrings(stringPali, "^[a-zA-Z]*$");
double percentage = (double) validStringCount / numOfStrings;
System.out.println(String.format("Percentage of words: %f%%", percentage));
int startWithCapitalCount = countStrings(stringPali, "^[A-Z].*");
percentage = (double) startWithCapitalCount / numOfStrings;
System.out.println(String.format("Words starting with capital letter: %f%%", percentage));
}
private static Integer countStrings(String[] stringPali, String pattern) {
int count = 0;
for (String str : stringPali) {
if (str.matches(pattern)) {
count++;
}
}
return count;
}
}

Unable to remove the last duplicate element in the array using 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;
}
}
}
}

Java array and nextInt(); do not work properly

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}
Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!
I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)

Filling a specifc part of a multidimensional string array(Out of bounds)

I'm making a database where you can enter in animals and the supplements that they need. I have to use a multidimensional array. The problem I'm running into is that when a user goes into entering data into the multidimensional array, I get an out of bounds error. I'm confused because I used the same methodology for the user to input the type of animal and the number of supplements needed, but when it gets to actually entering the supplement, I introduced and array hold to keep the supplements for each animal organized. For a more visual reference, my logic wanted to be like this:
Names
Animal Type 1 Supplement 1
The Animal types go down the first column while the supplements fill in a horizontal fashion on each animal. I'll post my code but specifically I've run into issues with the array out of bounds. I suspect it has to do with how I initialized the multi array, but I'm unsure at this point. Any help would be greatly appreciated!
//Nicholas Stafford
//February 1, 2016
//This program will allow user input of up to any number of animals and dietary information and then allow the user to display that information when searching the database
import java.util.Scanner;
import java.util.Arrays;
public class inventory {
public static void main(String[] args)
{
//Initial variables
int choiceent;
int numAnimals = 0;
int numDiet = 0;
int ArrayHold = 0;
boolean isNum;
boolean isNum2;
boolean quit = false;
//Scanners needed for input
Scanner choice = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
//Initial value needed to enter animals into database
System.out.println("Enter the number of animals you wish to enter:");
do
{
if(input1.hasNextInt()) {
numAnimals = input1.nextInt();
isNum = true;
}
else {
System.out.println("Please enter an integer value!");
isNum = false;
input1.next();
}
}
while(!(isNum));
System.out.println("You are entering " +numAnimals+ " animals.");
//Multidimensional array
String [][] ZooBase = new String [100][100];
//Array for data types
int numDietA[] = new int [numAnimals];
do{
System.out.println("1. Enter the names of each animal");
System.out.println("2. Enter the dietary information");
System.out.println("3. Search the array for information");
System.out.println("4. Close the program");
choiceent = choice.nextInt();
switch(choiceent)
{
case 1:
//Data validation for name
for(int i = 0; i < numAnimals; i++)
{
System.out.println("Enter the type of animal for animal " +i+ "");
while(!input2.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a type of animal!");
ZooBase[i+1][0] = input2.nextLine();
}
ZooBase[i+1][0] = input2.nextLine();
}
//Display Names
System.out.println("Names");
for(int j = 0; j < numAnimals; j++){
System.out.println(ZooBase[j+1][0]);
}
break;
case 2:
for(int j = 0; j < numAnimals; j++)
{
System.out.println("How many supplements does the " +ZooBase[j+1][0]+ " need?");
do
{
if(input3.hasNextInt()) {
numDietA[j] = input3.nextInt();
isNum2 = true;
}
else {
System.out.println("Please enter an integer value!");
isNum2 = false;
input3.next();
}
}while(!(isNum2));
}
for(int k = 0; k < numAnimals; k++)
{
ArrayHold = k+1;
for(int m = 0; m < numDietA[m]; m++ )
{
System.out.println("Enter item " +m+ " for the " +ZooBase[m+1][0]+ "");
while(!input4.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a supplement (No integers)!");
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
}
break;
case 3:
break;
case 4:
quit = true;
break;
default:
System.out.println("Invalid option!");
break;
}
}while(choiceent != 4);
}
}
Once an array is initialized, its size can't be changed. To make sure this does not happen, use ArrayList<>, which does not have fixed bounds. You can find the syntax + all details here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Hope that helps!
ps. you can also initialize just 1 scanner input and use it throughout

How to add array values

How do I add an array with several methods together
public void inputArray() {
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter the number of invoices: ");
numInvoices = keyboard.nextInt();
Invoices = new Invoice[numInvoices];
int BillTotal = 0;
for(int i = 0; i < numInvoices; i++){
Invoices[i] = new Invoice();
Invoices[i].setCompanyNameFromUser();
Invoices[i].setBillAmountFromUser();
Invoices[i].SetDateFromUser();
BillTotal = BillTotal + Invoices[i].setBillAmountFromUser;
In this case I want to add up the values input by the user in the setBillAmountFromUser method.
This program block may help you
public void inputArray()
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter the number of invoices: ");
int numInvoices = keyboard.nextInt();
int BillTotal=0;
Invoice Invoices[numInVoices];
for(int i=0;i<numInVoices;i++)
{
Invoices[i]=new Invoices();/*Your Code*/
BillTotal+=Invoices[i].setBillAmountFromUser();
}
System.out.println("BillTotal="+BillTotal);
}
public int setBillAmountFromUser()/*Example Code block/*
{
/*your code */
return 5;//Example Return value
}

Categories