else is not working when called by function - java

public static void main(String[] args) {
//For String
Scanner input = new Scanner(System.in);
//For Letter
Scanner word = new Scanner(System.in);
String name;
//Input For a String
System.out.println("Enter A String");
name = input.nextLine();
//Input For a Char
char letter[] = new char[3];
System.out.println("Enter a Letter You Want to Search ");
for(char c : letter)
letter = word.nextLine().toCharArray();
elfish(letter, name);
}
public static void elfish(char letter[], String name) {
if(name.toLowerCase().contains(name.valueOf(letter).toLowerCase())) {
System.out.println("Yes The Letter Contains Elfish");
} else {
System.out.println("You're Word is not in this String");
}
}
i m making the program which is near to completion. It actually searches the desired letter in the string and if condition is true is prints the "if block" and if condition is false "else block" should run but actually its not working now. only "if block" is working. "else block" was also working fine until it was directly placed in main function. please tell me where what is wrong.

You're trying to iterate through letter before putting anything in the array. If you take out the for loop, (leaving the assignment of letter) the code should run properly in many cases. I do not know how you want to validate input.
I'm guessing you are new. Learning to use a debugger can be overwhelming, but it is a powerful tool. It'll be slightly different for every debugger and IDE but the process is the same.
A little more info here: Breakpoints and step by step debug in Java?
However, in this instance finding a guide for your IDE on Google might be the best option.

Related

How do I create a while loop in java that will end the game once the two user inputs match?

I have been trying to create a game that asks the user to type in 2 three-letter words; the program is supposed to give clues for how close the words match by splitting them up and stating if the letters come before, or after, each other in the alphabet.
The game is nearly done, but my problem shows up when I try to start a new turn after one guess. I need some kind of while loop, but I've rearranged blocks of the code so many times that I feel like it made the entire thing more convoluted. The prompt for the second user to answer a question, as well as the clue, should be repeated every time the two inputs don't fully match.
Example Output when the two user inputs are cat and fan: after, a, before
The "after" shows that the letter comes after the user's letter in the alphabet, and the "before" shows that the letter comes before the user's letter.
EDIT: I have taken the answers into account as much as I can, thank you so much. So far, I have implemented a do while loop and tried to fix my variables. In the end, I feel that I may have to create an object to be able to recopy the code of the user inputs after a certain conditional statement would be set to false.
My new issues are
1. The compiler cannot find the symbols x1,y1,z1,x2,y2, and z2 whenever I have the user inputs inside the do while loop.
2. If I tried to make a new object, I would be rewriting & rearranging more than what might be necessary.
This is still ongoing, and as I continue to work on it I will keep updating this post.
(EDITED CODE -- I saved the original code which I can send to anyone who would like to see it.)
import java.util.Scanner;
class Main{
public static void main(String[] args) {
System.out.println("Guess The Word\n(requires two players)");
System.out.println("If the letter in each word matches, the letter will be reprinted.");
System.out.println("If the letter guessed doesn't match, either \"before\" or \"after\" will print.");
Scanner in1=new Scanner(System.in);
//Scanner in2=new Scanner(System.in);
try{
boolean correct1=false; boolean correct2=false; boolean correct3=false;
int indication=0;
//asks for user input and stores in substrings
do{
System.out.print("First Player, enter a three letter word: ");
String user1=in1.nextLine();
String x1=user1.substring(0,1);
String y1=user1.substring(1,2);
String z1=user1.substring(2,3);
System.out.print("Second Player, enter a three letter word: ");
String user2=in1.nextLine();
String x2=user2.substring(0,1);
String y2=user2.substring(1,2);
String z2=user2.substring(2,3);
}
while(!correct1||!correct2||!correct3);
//possible end to loop
// if(user1==user2){indication=1;}
// else{indication=0;}
//comparisons of each letter
int comp;
int comp2;
int comp3;
comp=x1.compareTo(x2);
comp2=y1.compareTo(y2);
comp3=z1.compareTo(z2);
//while1=(comp!=0);
//while2=(comp2!=0);
//while3=(comp3!=0);
//if statement 1
if(comp==0){
System.out.print(x1);
correct1=true;
}
else{
// System.out.println(comp);
if(comp>0){
System.out.println("before, ");
}
else{
System.out.print("after, ");
}
}
//if statement 2
if(comp2==0){
System.out.print(y1);
correct2=true;
}
else{
// System.out.println(comp);
if(comp2>0){
System.out.println(", before, ");
}
else{
System.out.print(", after, ");
}
}
//if statement 3
if(comp3==0){
System.out.print(z1);
correct3=true;
}
else{
// System.out.println(comp3);
if(comp3>0){
System.out.println(", before");
}
else{
System.out.print(", after");
}
}
//ignore else{System.out.print("Congratulations!");}
}
finally{in1.close();}/* in2.close();}*/
}
}
Maybe declare 3 booleans (1IsCorrect, 2IsCorrect, 3IsCorrect) set them default to false and in the if(comp/comp1/comp2 == 0) statements after printing the value set the corresponding boolean to true.
then put it in a do while(!1IsCorrect || !2IsCorrect || !3IsCorrect)
declare a variable perhaps for isFirstRun before loop and instantiate it to true at the declaration, then set to false at the very end.
Make an if !isFirstRun statement and add in the code there to ask for the next guess
Hope this works

Using scanner.next() outside loop yields weird results

Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:
public static void printStem(String word) ...
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);
while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}
This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).
Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so
public static void printStem(String word) ...
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}
When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)
Some explanation about hasNext():
Returns true if this scanner has another token in its input.
This method may block while waiting for input to scan.
The scanner does not advance past any input.
In your first piece of code
you scan for a word: String word = keyboard.next();
You print it: printStem(word);
You enter into a while loop which waits until you give some input: keyboard.hasNext()
In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.
Then you do a next read by next().
Explanation for next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Hence you get a weird behavior.
This will yield really weird results
Yeah, because the logic is wrong.
You get the input
String word = keyboard.next();
print it
printStem(word);
then print it again, and ask for another word:
while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.
as this should behave identical
No it shouldn't. You reversed the order of operations in the while-loop body.

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: ");
}

String.replace() method not printing full string in java

I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.

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