I have a question about writing a code that can check if what the user inputs (a string) is a duplicate of a string that an array already stored:
First of all I want to point out I checked with the question on here about duplicates but they are either answered with importing packages other than Scanner or checking duplicates in an already int or string stored arrays. This is different:
int numberOfPigs = Integer.parseInt( keyboard.nextLine() );
Pigs pigArray = new pigs[numberOfPigs];
for (int i = 0; i < pigArray.length; i++){
System.out.println("Pig name: " + (i+1));
String name = keyboard.nextLine();
String [] tempArray = new String [numberOfPigs];
tempArray[i]=name;
for (int k = i+1; k < pigArray.length; k++){
while (tempArray[i].equals( tempArray[k])){
System.out.println("The ID is duplicate.");
tempArrays[i] = keyboard.nextLine();
}
System.out.println("Not a duplicate! Yay.");
}
...code not over. the for loop with int i still has to go through several inputs from user before looping back to the beginning and go through i++ with taking in the next pig name. The rest part of the code I have no problem with, it's just that whenever i run this code, the duplicates are still allowed in... Any tips are appreciated. Thank you.
You made 2 mistakes in your code.
You were redeclaring your tempArray in your initial for loop.
You were counting up in your k loop when you should have been counting down.
int numberOfPigs = Integer.parseInt(keyboard.nextLine());
Pigs pigArray = new pigs[numberOfPigs];
String[] tempArray = new String[numberOfPigs]; // I moved this here see
// comment below
for (int i = 0; i < pigArray.length; i++) {
System.out.println("Pig name: " + (i + 1));
String name = keyboard.nextLine();
// first problem was you were redeclaring your tempArray here
// thereby erasing previous elements over every iteration of i
tempArray[i] = name;
for (int k = i - 1; k >= 0; k--) { // you need to count backwards
//you only check what was already entered for duplicates
// you were doing the opposite
while (tempArray[i].equals(tempArray[k])) {
System.out.println("The ID is duplicate.");
tempArray[i] = keyboard.nextLine();
}
System.out.println(" Not a duplicate! Yay.");
}// k loop
}// i loop
int numberOfPigs = Integer.parseInt( keyboard.nextLine() );
Pigs pigArray = new pigs[numberOfPigs];
for (int i = 0; i < pigArray.length; i++){
System.out.println("Pig name: " + (i+1));
String name = keyboard.nextLine();
String [] tempArray = new String [numberOfPigs];
tempArray is now an array with numberOfPigs, where each element is null.
tempArray[i]=name;
Now the first element in tempArray is the user-input name, but all other elements are still null.
for (int k = i+1; k < pigArray.length; k++){
Why are you using pigArray.length, yet you are not using pigArray in the loop at all?
while (tempArray[i].equals( tempArray[k])){
In fact, you're comparing the first element in the array, which is not null (it's the user input), against all the other elements, which are null! Of course it won't think anything is a duplicate, because you're checking the it against a whole bunch of nothing.
Since the user-input name is never equal to null, that is being falsely interpreted as "not a duplicate", and allowed through.
System.out.println("The ID is duplicate.");
tempArrays[i] = keyboard.nextLine();
}
System.out.println("Not a duplicate! Yay.");
}
Related
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
I can't get Collections.rotate to work. When I enter qwerty into userInputCharacters and run this code, it just ends up outputting qwerty again. Any recommendations?
Collections.rotate(Arrays.asList(userInputChararacter), 2);
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
UPDATE: Here is my full program.
import java.util.*;
public class WrapAround
{
public static void main(String[] args) throws java.io.IOException
{
//Create a scanner to read the users input.
Scanner userInput = new Scanner(System.in);
//Get the amount of characters the user wants to input.
System.out.println("How many character do you want to enter?");
int characterAmount = userInput.nextInt();
//Get and put the user's characters into an array.
System.out.println("Please enter your " + characterAmount + " characters.");
String userInputString;
userInputString = userInput.next();
char[] userInputChararacter = new char[characterAmount];
for(int index = 0; index <= characterAmount - 1; index++)
userInputChararacter[index] = userInputString.charAt(index);
//Get what number character the user wants to start with.
System.out.println("Which character do you want to start with?");
int startingCharacterIndex;
startingCharacterIndex = userInput.nextInt();
startingCharacterIndex--;
//Give the user their characters in order.
System.out.println("Here are all your characters, beginning with number " + (startingCharacterIndex + 1) + ".");
userInputChararacter = Collections.rotate(Arrays.asList(userInputChararacter), (startingCharacterIndex - 1));
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
/*
for(int index = startingCharacterIndex; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
for(int index = 0; index <= startingCharacterIndex - 1; index++)
System.out.print(userInputChararacter[index]);
*/
System.out.println();
}
}
The reason it doesn't work is that Arrays.asList(new char[]{'q','u','e'}) will create a list of size 1, not 3. It's different from Arrays.asList('q','u','e') where elements will be correctly autoboxed to Character and list of size 3. Consequently your rotation is not going to change anything.
You should create your own List<Character> instance by adding elements or creating a wrapper class for the underlying array.
Or, perhaps easier to eliminate char altogether and represent even single chars as Strings.
I recently started coding in Java and my coach gave me an exercise where I have to re-create the Mastermind game. To give an overview of this game: the computer creates an array with X random integers, and the user gets to input X integers as well. Location matters. The users scores "Gold" if he guesses an integer that is in the same spot as the computer generated array. If the integer is present in the array, but in the wrong spot, the users gets a "Silver" score. If the integer is not present in the array at all, the user gets a "NotFound" score. The final array should give the user a score for each place in the array, e.g. (Gold, Silver, NotFound)
I have tried to make a nested loop that scores the users guesses. It captures the score in a different array (yourScore[]). User guesses are captured in array "guessednums[]" and the computer generated array is called "nums[]". The size of all arrays has been set with a variable prior to the mentioned code.
What I want the code to do is to first check whether a user's guess matches with the computer choice on the same spot, and if that is the case set the matching space in the yourScore array to "Gold". Then, if the guess does not directly match, I want a loop to check whether the user guess is present in ANY place of the computer generated nums[] array, and to score it as "Silver" if that is the case. Finally, if this is not the case, I want the yourScore[] place to be set as "NotFound".
Matching guesses are properly scored as "Gold". The problem I am encountering is that sometimes the loop will not properly score a guess as "Silver", but instead mark it as "NotFound". I suspect that this has to do with the loop not properly initialising. I have read multiple questions on Stack Overflow and other articles as well, and played around with my code, but I keep running into similar issues.
I would love to get a second opinion on the code and see what I have done wrong.
package Mastermind;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Mastermind {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
int size = 3; // Allows you to set the size of the arrays in the game
int[] nums = generateNumbers(size); //Stores the computer choice 3-tuple
int[] guessednums; //Stores the guessed 3-tuple
int iteration = 0; //Keeps track of the # of guesses so far
boolean correctAnswer; //true if the guessed tuple matches the computer choice tuple
//Set array size
//The game starts here
while (true){
iteration++;
System.out.println("Iteration #" + iteration);
guessednums = guessTheNumbers(size);
correctAnswer = yourScore(nums, guessednums, size);
if(correctAnswer) break;
}
//Printing the result
printResults(iteration, nums);
}
private static void printResults(int iteration, int[] nums) {
System.out.println("************************************************************"); // Print final result if users has a completely matching guess
System.out.println("************************************************************");
System.out.println("The correct answer was " + Arrays.toString(nums));
System.out.println("It took you " + iteration + " iterations to find the answer!");
}
private static int[] guessTheNumbers(int size) {
System.out.println("Please your ordered guess (press enter after each):");
int[] guessednums = new int[size]; // Initialise array for user choices
for (int i = 0; i < size; i++){ // Loop that creates the array of user input
guessednums[i] = userInput.nextInt();
}
System.out.println(Arrays.toString(guessednums));
return guessednums; // Return array for user guessed numbers array to main method
}
public static int[] generateNumbers(int size){
int[] nums = new int[size]; // Initialise array for computer choices
Random rn = new Random(); // Create new variable for randomised computer choices
for (int i = 0; i < size; i++){ // Loop that creates the array of computer choices
nums[i] = rn.nextInt(9) + 1;
}
System.out.println(Arrays.toString(nums)); // Temporary to print array
return nums; // Return array for computer generated numbers array to main method
}
public static boolean yourScore(int[] nums, int[] guessednums, int size){
String[] yourScore = new String[size]; // Initialise array for user choices
for(int i = 0; i < size; i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
if (guessednums[i] == nums[i]){
yourScore[i] = "Gold";
} else {
yourScore[i] = "NotFound";// in case is not found it stays that way
for(int j = 0; j < size; j++){
if (guessednums[i] == nums[j]){
yourScore[i] = "Silver"; // found one! break the loop and keep checking numbers
break;
}
}
}
}
if (yourScore[0] == "Gold" && yourScore[1] == "Gold" && yourScore[2] == "Gold"){ // Marks the input as true or false depending on if it matches with the computer choices
boolean correctanswer = true;
return correctanswer;
} else {
System.out.println("Your score is " + Arrays.toString(yourScore) + "!");
System.out.println("************************************************************");
boolean correctanswer = false;
return correctanswer;
}
}
}
The problem comes with the logic. I find useful to put the logic into words:
For each number in the array:
1. Check if the numbers are equal in that position (Gold)
2 else, for each number in the array, check if that number is equal to another in the array
3. If that number is in it, break the loop (Silver)
4. else, mark it as not found (NotFound).
the code would be like this:
for(int i = 0; i < size; i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
if (guessednums[i] == nums[i]){
yourScore[i] = "Gold";
} else {
yourScore[i] = "NotFound";// in case is not found it stays that way
for(int j=0;j<size<j++){
if (guessednums[i] == nums[j]){
yourScore[i] = "Silver"; // found one! break the loop and keep checking numbers
break;
}
}
}
}
I think you mixed up the outer and inner index meaning. Try this:
for(int i = 0; i < size; i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
for(int j = 0; j < size; j++){
if(i == j) {
if (guessednums[i] == nums[j]){
yourScore[i] = "Gold";
}
} else {
if (guessednums[i] == nums[j]){
yourScore[i] = "Silver";
} else if (guessednums[i] != nums[j]){
yourScore[i] = "NotFound";
}
}
}
}
Gold is only possible if i == j ...
HTH and always better for readers, if indentation is plausible and thus easy for the eyes ...
Not elegant but simple:
for(int i = 0; i < 5; i++){
yourScore[i] = "NotFound";//most likely
}
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(guessednums[i]==nums[j]) {
yourScore[i] = "Silver"; //quite likely
}
}
}
for(int i = 0; i < 5; i++){
if(guessednums[i]==nums[i]) {
yourScore[i] = "Gold"; //very unlikely
}
}
I want to make a list going to n numbers depending on user input. I then want to put a second number in each place and print the entire table. As for testing I have tried with a length 4 and numbers 1,2,3,4 but I get a error: ArrayIndexOutOfBounds. I wanted it to print 1,2,3,4.
Scanner keyboard = new Scanner (System.in);
System.out.println("Whats the length of the table?");
int lengde = keyboard.nextInt();
int[] minTabell = new int[lengde];
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
System.out.println(minTabell);
keyboard.close();
Indexes in Java arrays are 0-based, while your for-loop starts from 1. So,
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
should be
for (int i =0; i < lengde; i++) {
// ^ ^^^^^^^^
System.out.println((i+1) + (" give a number"));
// ^^^
minTabell[i] = keyboard.nextInt();
}
As for printing the content of the array, I suggest you use
for (int i : minTabell)
System.out.println(i);
In Java array indexing starts at 0. The first element is positioned at minTabel1[0]. Your for-loop runs from 1 to lengde + 1, which means that you will try to fill a position outside of the array.
The first element of an array has the index 0. The last valid index of your array is lengde-1.
Try this:
for (int i=0; i < lengde; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
To print the array, i suggest the following:
System.out.println(Arrays.toString(minTabell));
String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem