Get Data by Given Index - java

While coding a program for employee-management, I need a method which spits out the corresponding data to a specific index (the number given by the user).
Already tried a lot of methods to make this happen, for example the one below, with no success:
public static void ausgabeIndex(int index, String[] nN, String[] vN, String[] adres) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert the number of the registered employees: ");
index = sc.nextInt();
for (int i = 0; i < nN.length; i++) {
if (nN[i].equals(index)) {
System.out.println(nN[index]);
System.out.println(vN[index]);
System.out.println(adres[index]);
}
}
}

It's unclear if there is more than one issue here, since you didn't say what the actual problem was, other than it doesn't work.
Also, your data here is a bit strange. This would be better suited as a class to encapsulate all the data instead of three string arrays.
I suspect, however, that this is part of your problem: nN[i].equals(index)
nN is an array of String, and index is an int. These will never be equal. They aren't the same data type.
To properly compare a String and an integer, you need to either convert the String to an int or the int to a String. Converting an int to a String is the safer option, so you could do this:
nN[i].equals(String.valueOf(index))
To do the opposite, converting a String to an int, you can use Integer.parseInt(String)
Integer.parseInt(nN[i]) == index
One more note:
public static void ausgabeIndex(int index
You are passing in index but immediately overwriting it with your Scanner.nextInt. You don't need it as a method argument.

You need to address the following things in your code:
Whenver you try to access an element from an array, make sure you check the bounds to avoid ArrayIndexOutOfBoundsException e.g. you have accessed vN[index] without checking whether index is less than vN.length. adres[index] also has the same problem.
nN[i] is a String while i is an int and therefore they can not be compared unless you change the one into the other. However, I'm sure you didn't mean to compare nN[i] with index. Looking at your program, it seems you want to compare nN[i] with nN[index].
Since you are already passing index as a parameter to the method, the following lines do not make sense unless you want to override the value of index. If you do not want to override the value of parameter, index, remove these lines.
Scanner sc = new Scanner(System.in);
System.out.println("Geben Sie bitte die Nummer des/der regestrierten Mitarbeiters/Mitarbeiterin ein: ");
index = sc.nextInt();
Alternatively, if you want to keep these lines in the method, remove the parameter, index. As I've mentioned above, keeping both of these makes sense only if you want to override the value of parameter, index.
Given below is the code incorporating these comments:
public static void ausgabeIndex(int index, String[] nN, String[] vN, String[] adres) {
if(index < nN.length) {
for (int i = 0; i < nN.length; i++) {
if (nN[i].equals(nN[index])) {
System.out.println(nN[index]);
if (index < vN.length) {
System.out.println(vN[index]);
}
if (index < adres.length) {
System.out.println(adres[index]);
}
}
}
} else {
System.out.printnl("The index, " + index + " is out of the bounds.");
}
}

Related

Why is method not working as I thought it would?

I am attempting to create a hangman game. I have everything working as I want so far with the exception of one method. This method is called processGuess and takes a String letter and two String arrays as parameters. The first array is an array called spaceArray and contains Underscores that match the length of the word being guessed (example: hello produces [ _ , _ , _ , _ , _ ]). The second array is called wordArray and contains the word the user is trying to guess.
The way I envision my method working is as follows:
Create an array that stores all guessed letters (guessArray)
Create a counter that keeps track of the number of guesses (guessCounter)
Use a for loop to iterate through each letter of the word and compare it with the letter the user guessed.
a. If the letter is in the word, add the letter to the correct index of the spaceArray
Compare spaceArray to wordArray
a. If equal, print something saying they won in x number of guesses
b. If not equal.
Print spaceArray
Call the method that asks user to guess the next letter
Call this method so that the new guessed letter is processed.
The problem is that when I recall this method, it does not contain the new letter but still contains the old letter. I am unsure of what I am doing wrong. This is the first time that I have tried using methods within a method.
Here is my method:
public static void main(String[] args) throws FileNotFoundException {
Scanner file = new Scanner(
new File("C:/FilesForJava/ScrabbleDictionary.txt"));
instructions();
String[] dictionary = createDictonaryArray(file);
String[] randomWord = getRandomWord(dictionary);
String[] underscoreArray = showSpaces(randomWord);
String letter = getGuesses();
processGuess(letter, underscoreArray, randomWord);
}
public static void instructions() {
System.out.println("Let's play hangman!");
System.out.println();
}
public static String[] createDictonaryArray(Scanner inputFile)
throws FileNotFoundException {
int wordCount = 0;
while(inputFile.hasNext()) {
String word = inputFile.next();
wordCount++;
}
String[] scrabbleDictionary = new String[wordCount];
Scanner file = new Scanner(
new File("C:/FilesForJava/ScrabbleDictionary.txt"));
while(file.hasNext()) {
for(int i = 0; i < wordCount; i++) {
scrabbleDictionary[i] = file.next();
}
}
file.close();
return scrabbleDictionary;
}
public static String[] getRandomWord(String[] dict) {
String word = dict[(int)(Math.random() * dict.length)];
String[] wordArray = new String[word.length()];
for(int i = 0; i < wordArray.length; i++) {
wordArray[i] = word.trim().substring(0, 1);
word = word.trim().substring(1);
}
return wordArray;
}
public static String[] showSpaces(String[] word) {
String[] spaceArray = new String[word.length];
for(int i = 0; i < word.length; i++) {
spaceArray[i] = "_";
}
System.out.println(Arrays.toString(spaceArray));
System.out.println();
return spaceArray;
}
public static String getGuesses() {
Scanner guess = new Scanner(System.in);
System.out.println("Guess a letter: ");
String letter = guess.next();
System.out.println();
//guess.close();
return letter;
}
public static void processGuess(String letter, String[] spaceArray,
String[] wordArray) {
int guessCounter = 0;
String[] guessArray = new String[spaceArray.length];
for(int i = 0; i < spaceArray.length; i++) {
guessCounter++;
guessArray[i] = letter;
String indexLetter = wordArray[i];
if(indexLetter.equalsIgnoreCase(letter)) {
spaceArray[i] = letter;
}
}
if(spaceArray.equals(wordArray)) {
System.out.println("Yes! You won in " + guessCounter + "guesses!");
}else {
System.out.println(Arrays.toString(spaceArray));
getGuesses();
processGuess(letter, spaceArray, wordArray);
}
}
You need to pass the new guess into your processGuess method. Try something like this:
else {
System.out.println(Arrays.toString(spaceArray));
String newLetter = getGuesses();
processGuess(newLetter, spaceArray, wordArray);
}
I think this method is trying to do too much. It's strange for it to read new input and call itself recursively -- I would have expected its caller to use a loop to solicit guesses from the player and call this method (which would not recurse) instead. The method might indicate by a return value whether the user had won.
Additionally, the code seems overly complex. For instance, what's the point of guessArray, which you instantiate and initialize but never use for anything?
Furthermore, it's strange that you use arrays of Strings instead of arrays of chars, since all your Strings seem to contain a single character each. (That might actually be appropriate if you are looking to accommodate surrogate pairs, but such a consideration seems a little out of character for the level of the task.)
In any event, the reason the recursive calls to your method see only the first letter guessed is that that's what you pass to them. The getGuesses() method does nothing to modify the local letter variable (nor can it do), and the method itself just passes along whatever was passed to it.
Well, it looks like you might have a couple of problems.
First, recursion is a very poor choice for this method, I think what you're looking for is a while loop where the condition changes when the strings are equal. Using recursion here needlessly increases the size of the stack as you call more and more methods, but never return from them.
Now as to your question, in the code you gave us, the variable letter never gets changed. I assume that get guesses returns a string? If thats true then you need to set letter equal to it.
I would also like to suggest that you use a char instead of a string.
public static void processGuess(String letter, String[] spaceArray,
String[] wordArray) {
while(true) {
int guessCounter = 0;
String[] guessArray = new String[spaceArray.length];
for (int i = 0; i < spaceArray.length; i++) {
guessCounter++;
guessArray[i] = letter;
String indexLetter = wordArray[i];
if (indexLetter.equalsIgnoreCase(letter)) {
spaceArray[i] = letter;
}
}
if (spaceArray.equals(wordArray)) {
System.out.println("Yes! You won in " + guessCounter + "guesses!");
break;
} else {
System.out.println(Arrays.toString(spaceArray));
letter = getGuesses();
}
}
}
You've written the method as a recursive method (probably not the best way to do it). The issue is that when a recursive method declares a local variable, each invocation of the recursive method has its own copy of the local variables.
Thus you call processGuess, which creates a guessArray. Then processGuess calls itself again, which has its own guessArray, and after this happens a few times, you'll have a stack that looks something like:
+--------------------------------------------------------+
+ processGuess#1 +
+ local variables: guessCounter#1, guessArray#1, i#1 +
+--------------------------------------------------------+ --> calls:
+ processGuess#2 +
+ local variables: guessCounter#2, guessArray#2, i#2 +
+--------------------------------------------------------+ --> which calls:
+ processGuess#3 +
+ local variables: guessCounter#3, guessArray#3, i#3 +
+--------------------------------------------------------+ --> which calls:
+ processGuess#4 +
+ local variables: guessCounter#4, guessArray#4, i#4 +
+--------------------------------------------------------+
When processGuess#4 modifies guessArray, it changes guessArray#4. But that has no effect on guessArray#3, guessArray#2, or guessArray#1. All of these are separate local variables, and they are references that refer to four different objects. Thus, when processGuess#4, processGuess#3, and processGuess#2 all return, the changes they've made to their own guessArray's are lost, and processGuess#1 will see only the changes that it, itself, has made to its own guessArray.
As I said, I wouldn't use recursion for this particular problem. But it's definitely a problem in other cases where recursion is the right way to do things. The solutions are: (1) declare the variable or object outside the recursive method, as an instance field in the object--then they will all be accessing the same variable; or (2) add a parameter to the recursive method so that the recursive invocations can share a reference to the same object.
[Note: The #1, #2 numbers I added are just to help explain things; they aren't part of any language syntax or anything like that.]

Comparing an array to two static values

So I am just doing something simple. I made a simple Java program where you enter your guess for what the roll will be which is stored in an array and then compared to two numbers generated randomly. So my question is how would I do the comparison of the array against the two number without referencing the exact index (i.e. not array[0]=number[1])? I am doing this mostly to figure out how array work. Also why is the else erroring?
public static void main (String [] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int [] guess= new int [2];
System.out.print("Enter " + guess.length + " values: ");
for (int i=0; i<guess.length;i++)
guess[i] = input.nextInt();
method(guess);
}
public static String method(int [] that){
int number1 = (int)(Math.random() * 6);
int number2 = (int)(Math.random() * 6);
for (int i =0;i<that.length;i++){
if(that[i]==number1 and that[i]+1==number2)
{
return "You got it";
}
else
{
return "try again";
}//end else
} //end for
}//end method
You cannot write and like that , if you want to AND two conditions write &&. Also in your if condition I think you mean to increment your index that[i+1]==number2 , you were incrementing the random number itself. So your if condition would look like:-
if(that[i]==number1 && that[i+1]==number2)
{
return "You got it";
}
else{
..
}
Also want to add that you output You got it or try again will not be visible to user, since you are just calling the method method(guess); from main() which returns a String but does not do anything with returned String. You have to write it like this to make the ouput visible on console.
System.out.println(method(guess));
You can check whether the array contains the element or not like this
Arrays.asList(that).contains(number1)
It will return true if the array contains the element else as false
if you want comparison of the array against the two number without referencing the exact index then the first thing that you can do is use enhance for loop to avoid indexing of array like this
for(int number: that){
// do your comparison while iterating numbers in that(array) as "number"
}

Why doesn't my string change?

public static void read(String a[], double b[], String c) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
while (in.hasNext()) {
int i = 0;
String id = in.next();
String name = in.next();
String lastname = in.next();
double grade = in.nextDouble();
if (name.substring(0, 2).equalsIgnoreCase(c)) {
a[i] = id + "\t" + name + "\t" + lastname + "\t" + grade;
b[i] = grade;
}
i++;
}
}
When I use this method with
String men[] = new String[501];
double menGrade[] = new double[501];
read(men, menGrade, "MR");
My men[0] is assigned a String but men[1] to men [500] are all null ...
You need to declare your variable i outside of the while loop to keep it incremented.
Right now you are
declaring it with value 0
assign the values to the 1st array position
increment i, and then
declare it again with value 0 at the next loop iteration.
SO, just change your lines:
while (in.hasNext()) {
int i = 0;
to
int i = 0;
while (in.hasNext()) {
Your code has also other issues which you should adress in some way.
I do not know why you initialize your array with a fixed size of 500 and also check some conditions before you add your men and grades to those Arrays. This will however lead to a few problems if you are not careful.
Right now you would have holes in your array whenever the if condition does not evaluate to true.
Also your program would crash if there is more than 500 entries in your file.
A rather good solution when dealing with dynamic data structures (so, when you do not know beforehand how many records you will have exactly), is to use a dynamic data structure.
In java you can have a look at java.util.List interface and probably java.util.ArrayList as a good implementation.
Here is also the java doc of that class: Java Doc
Here you find more on the collections api which are a good thing for dynamic data structures: Collections - List tutorial
while (in.hasNext()) {
int i = 0;
...
This will RESET i each time you start the while loop and you always overwrite a[0] and b[0].
swap these two lines! (so the int i = 0; comes before the loop:
int i = 0;
while (in.hasNext()) {
...
You should increment i in your if statement and not always like you do now. You don't want holes in your men array.
This simply means, either your loop is executing only once.
Or, if block in loop is exceuting only once.
Dependecy is on the content of file you are importing and your if condition.
I'm pretty sure that something is wrong with your "data.txt" that caused the while loop to execute only once. Otherwise, I don't see any mistake in the code.
Why don't you check the value of i during the execution of the program?
If your data.txt file contains One single line then the corresponding while will be running for once populating the first element of the array i.e men in your case
The reason is this:
while (in.hasNext()) {
int i = 0;
...
i++;
}
you are destroying and creating i variable each time loop is executed effectively reseting it to 0 each time. Asides from notes from other answers you can simply move i outside the loop:
int i = 0;
while (in.hasNext()) {
...
i++;
}
Now I can't run in myself, but I see
while (in.hasNext()) {
int i = 0;
//other
a[i] = id + "\t" + name + "\t" + lastname + "\t" + grade;
b[i] = grade;
}
i++;
If you use a counter i over an array/Collection, generally you have to give a greater scope to counter.
if the counter is inside the while, at every iteration you recreate the counter and you point always at the same element of array
The/one solution can be:
int i=0;
while (in.hasNext()) {
//etc

Getting The Array Index From string.toCharArray()

I am making an inefficient calculator type of program that takes values from user defined arrays and plugs them into an equation that the user also defines. To do this I needed to make my program change my string to a char array, the problem? I have it so that users must use A1-10 to reference the definded index and I cannot find a way to make the program search the next array for the number to specify what array the program is accessing.
out.println("Please input a string of commands in a format similar to this: ");
out.println("([A1]-[A2]=) or ([A8]+[A6]=) or ([A1]-[A4]+[A7]*[A10]/[A3]=)");
out.println("Use only the numbers 1-10 when referencing an array. \n You may always type in 'Help' if you need help. ");
String eString = scn.nextLine();
if ("help".equals(eString)) {
out.println("Figure it our yourself...");
} else {
for (char c: eString.toCharArray()) {
if (c == 'A') {
}
}
the code got a little jumbled up while changing code and I haven't taken the time to make it look nice and pearly again.
If you need the index you should just use a normal for loop instead of an enhanced for loop.
char[] input = eString.toCharArray();
for(int i = 0; i < input.length; i++) {
if(input[i] == 'A'){
// You know the index of A here.
}
}
You should also use "help".equalsIgnoreCase(eString) when comparing with help so that they can enter either "Help" or "help" (link to doc)

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Categories