Check for value in array - java

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.

Related

I need help figuring out how to copy a person's response 100 times in a row

import java.util.Scanner; // *Has to be outside of brackets!*
public class Lab_1_3_Class_oops {
public static void main(String[] args) {
//I need to request a person's first and last name, then copy it on individual lines after they have entered their input
//Variables
Scanner sc = new Scanner(System.in);
//Requesting a name
System.out.print("Please write your first and last name.\n");
//Allowing a name input
sc.nextLine();
//I get as far as allowing text to be entered, but I can't figure out a way to keep that text in the memory long enough to get it copied 100 times without making the person type it 100 times
}
}
I am not looking for direct answers. I just want to know if what I want is possible with the way I have started and how I would even begin to try something like this.
Get the name input as a String and use a for loop to print it. I hope I wasn't too direct.
You need to declare a variable to hold the user's input. Then, you can use a for loop to do whatever you want any number of times.
String name = sc.nextLine(); // Declare a String variable to hold the value
for(int i = 0; i < 1337; i++) { // Use a for loop
// do something
}
Declare a variable to hold the user's input, then put it in a loop(print it from there)
Thank you all so much! The way I fixed it was by declaring
int num = 1;
and then creating a while loop
while (num <= 100) {
System.out.println(name);
num = num + 1;
}
I really appreciate everyone's help without actually telling me the answer.

Scanner.next() and hasNext() creating infinite loop when reading from console [duplicate]

I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}

java lexicographically sort three words

I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.
public class SortWords {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;
System.out.println("Enter three words seperated by white space");
firstWord = userInput.next();
System.out.println(firstWord);
secondWord = userInput.next();
System.out.println(secondWord);
thirdWord = userInput.next();
System.out.println(thirdWord);
}
}
Then try to read as an array elements then sort that array
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] strings = new String[3];
for (int i = 0; i < strings .length; i++)
{
System.out.println("Please enter name");
strings [i] = input.next();
}
}
Arrays.sort(strings);
"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."
This is incorrect.
First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)
Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.
You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.

list.add(String) in LinkedList doesnt work properly for me

I want write program with this functionality:
User will input how many things he have. He will input these things and things will be added to the list.
I made this code :
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
LinkedList<String> list= new LinkedList<String>();
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=1;c<=size;c++) list.add(input.nextLine().toString());
System.out.printf("%s",list);
}
}
For example Output for number 5 looks like this:
[, 1st Inputed, 2nd Inputed,3rd Inputed, 4nd inputed]
I want to know why the first String in the list is empty and it lets me input less things that I want. Thank you for your help.
Your code should be like this:
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=0 ;c < size; c++)
{
String s = input.next();//use next() instead of nextLine()
list.add(s);
}
System.out.printf("%s",list);
}
}
Scanner.nextLine() as described in official document is:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
After nextInt() is called it isn't properly terminating the allocated line of memory. So when nextLine() is called first time it is actually terminating the previous line that actually had value in it -- entered via nextInt() rather than taking in a new String value.That's why the String at index 0 of list is blank. So , in order to carry on reading the entered value rather than the previous blank line (because of non-termination of value returned by nextInt()) you can use Scanner.next() which according to official document states that:
Finds and returns the next complete token from this scanner.
The issue is that input.nextInt() does not consume the trailing newline, so the first input.nextLine() returns an empty string.
There are several ways to work around this. I'll leave it as an exercise to figure out how best to do it.

How to get out of while loop in java with Scanner method "hasNext" as condition?

I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}

Categories