import java.util.Scanner;
public class inputTesting {
public void checkone(){
String input="Hello Word";
Scanner s=new Scanner(input);
while (s.hasNext()){
String word=s.next();
System.out.println(word);
}
s.close();
}
public void checktwo(){
System.out.print("Enter the line: ");
Scanner s=new Scanner(System.in);
while (s.hasNextLine()){
String k=s.nextLine();
Scanner sc=new Scanner(k);
while (sc.hasNext()){
String word=sc.next();
System.out.println(word);
}
sc.close();
break;
}
s.close();
}
public void checkthree(){
System.out.print("Enter the line which should combine using '_': ");
Scanner sy=new Scanner(System.in);
while(sy.hasNextLine()){
String sk=sy.nextLine();
Scanner sn=new Scanner(sk);
sn.useDelimiter("_");
while (sn.hasNext()){
String word=sn.next();
System.out.println(word);
}
sn.close();
break;
}
sy.close();
}
}
class inputs{
public static void main(String args[]){
inputTesting it=new inputTesting();
it.checkone();
it.checktwo();
it.checkthree();
}
}
Steps i have tried:
- Removed the new line print from checktwo() method i.e: System.out.println(word);
- added extra : sy.nextLine() method, to consume if any lines were there previously before entering the checkthree() while loop.
Both the points were not worked.
Solution i have tried is : passed the input directly from it.checkthree("This_is_my_name_"); and hardcoded checkthree() method too , and it worked corrcetly.
Expecting:
Why my actual code is not working ? due to multiple scanner objects? even tough i need a solution using scanner object only, please provide your recommendations.