Java program not terminating when using scanner with System.in - java

I am unable to terminate my java program which takes some strings as input, below is the code I used to process the input
import java.util.Scanner;
public class EPALIN {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while((p=sc.nextLine())!=null)
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i =0;
int j = st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
Even using
while((p=sc.nextLine())!="")
didn't work, its a problem from SPOJ problemId EPALIN

Do something like this
while(!(p=sc.nextLine()).equals("")) {
// ...
}
I try your code with the while i'm using and it's seems to work.
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while(!(p=sc.nextLine()).equals(""))
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i=0;
int j=st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}

You should use hasNext()
String delimiter = "\r\n|\r"; //Or try System.getProperty("line.separator");
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(delimiter);
while (scanner.hasNext()) {
String p = scanner.next();
// ...
}
}

See the Scanner documentation. Scanner.nextLine() won't return null. If the input ends (for instance, the judge has piped a file to stdin, and the file ends), it will instead throw NoSuchElementException. If it doesn't, nextLine() will block.
Ordinarily what you could do here, because the the problem description states that each test case will be on its own line is (similar to what CandiedOrange suggested):
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
However, the problem also states:
Large I/O. Be careful in certain languages.
In contest problem lingo, this means "don't use Scanner." For fast I/O, you have a couple of options, but something like the following should work fine while keeping you under the time limit:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line;
while ((line = in.readLine()) != null)
doSomething(line); // etc
}
Note that you will most likely also have to collect all of your output and print it at the end, rather than making a bunch of System.out.println(), which have overhead that you can avoid by only printing once.

Related

Is there a way for my spellchecker to properly work

The problem is my spellchecker, that I am trying to make. I have a dictionary file that contains large amount of words to compare with the user input so it can detect any possible spelling errors. The problem with mine, is that regardless of what you type it will always say that the spelling is incorrect when it is not. Is there any solution or a better method to detect selling errors of the user input.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
final String theDictionary = "dictionary.txt";
String[] words = dictionary(theDictionary);
boolean correctSpelling = checking(words, userWord);
if (!correctSpelling)
{
System.out.println("Incorrect spelling");
}
else
{
System.out.println("The spelling is correct");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException
{
final String fileName = "dictionary.txt";
Scanner dictionary = new Scanner(new File(fileName));
int dictionaryLength =0;
while (dictionary.hasNext())
{
++dictionaryLength;
dictionary.nextLine();
}
String [] theWords = new String[dictionaryLength];
for ( int x = 0; x < theWords.length ; x++)
dictionary.close();
return theWords;
}
public static boolean checking(String[] dictionary, String userWord)
{
boolean correctSpelling = false;
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
correctSpelling = true;
}
else
correctSpelling = false;
}
return correctSpelling;
}
}
The result I get is:
Please enter a String
hello
Incorrect spelling
As you can see the, even though my spelling was correct, it gives an error that the spelling was incorrect. Any help would be great and thank you in advance.
Yes. Return from checking on true. As you have it now, it can only be true if the last word matches. Like,
public static boolean checking(String[] dictionary, String userWord) {
for ( int i =0; i < dictionary.length; i++) {
if (userWord.equals(dictionary[i])) {
return true;
}
}
return false;
}
Also, you need to populate your dictionary by adding words to your array.
And, I would prefer try-with-resources over explicit close() calls. Something like,
public static String[] dictionary(String filename) throws FileNotFoundException {
final String fileName = "dictionary.txt";
int dictionaryLength = 0, i = 0;
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
++dictionaryLength;
dictionary.nextLine();
}
}
String[] theWords = new String[dictionaryLength];
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords[i] = dictionary.nextLine();
i++;
}
}
return theWords;
}

How do I parse through java source code and not store blank lines?

This is my method for adding each line of code:
public static void String(){
File f = new File("src/testClass.java");
try {
Scanner s = new Scanner(f);
s.useDelimiter("\\n");
while(s.hasNextLine()){
String st = s.next();
if(!st.equals("\\p{Space}")) System.out.println(st);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Here is the testClass.java
public class testClass {
public static void main (String[] args){
int someNum = 1; //comment
String someStr = "haha";
/* final double pi = 3.14159;
*
*/
}
public static void uselessMethod(int someNum){
boolean isUseless1 = true;
}
}
When I use this class to test my parser, it doesn't skip over the blank space after the brace underneath the closing bracket for main. What needs to be done to not get it to be stored? What is the more appropriate if statement to get it to not store that blank line, while acknowledging that it is a line rather than skipping over it completely? I want to keep track of the line number while not storing the blank lines.
You want to use the matches() method instead of equals():
if(!st.matches("^\\p{Space}*$")) System.out.println(st);
I've also modified your regular expression a little bit. It should now exclude all lines that are empty or contain only whitespace.
I usually just skip empty line:
public static List<String> fileToList(String patch) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(patch));
String line ="";
List<String> result = new ArrayList<>();
while ((line = br.readLine()) != null) {
/*
* Just skip empty line
*/
if (line.isEmpty()) {
continue;
} else {
result.add(line);
}
}
return result;
}

Capitalize every word using Scanner(System.in) Java

This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}

Using a method to call individual strings from an array (looping)

This is the question from my assignment that I am unsure of:
The class is to contain a public method nextWord(). When a new line is read, use the String method .split("\s+") to create an array of the words that are on the line. Each call to the nextWord() method is to return the next word in the array. When all of the words in the array have been processed, read the next line in the file. The nextWord()method returns the value null when the end of the file is reached.
I have read the file, and stored each individual string in an array called tokenz.
I'm not sure how I can have a method called "nextWord" which returns each individual word from tokenz one at a time. Maybe I don't understand the question?
The last part of the question is:
In your main class, write a method named processWords() which instantiates the MyReader class (using the String "A2Q2in.txt"). Then write a loop that obtains one word at a time from the MyReader class using the nextWord() method and prints each word on a new line.
I've thought of ways to do this but I'm not sure how to return each word from the nextWord method i'm supposed to write. I can't increase a count because after the String is returned, anything after the return statement cannot be reached because the method is done processing.
Any help would be appreciated, maybe I'm going about this the wrong way?
Can't use array lists or anything like that.
Here is my code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class A2Q2
{
public static void main (String [] args)
{
processWords();
}
public static void processWords()
{
MyReader reader = new MyReader("A2Q2.txt");
String[] words = new String[174];
words[0] = reader.nextWord();
System.out.println(words[0]);
}
}
class MyReader
{
static String name;
static BufferedReader fileIn;
static String inputLine;
static int tokensLength = 0;
static String[] tokens;
static int counter = 0;
// constructor.
public MyReader(String name)
{
this.name = name;
}
public static String[] readFile()
{
String[] tokenz = new String[174];
int tokensLength = 0;
try
{
fileIn = new BufferedReader (new FileReader(name));
inputLine = fileIn.readLine();
while(inputLine !=null)
{
tokens = inputLine.split("\\s+");
for (int i = 0 ; i < tokens.length; i++)
{
int j = i + tokensLength;
tokenz[j] = tokens[i];
}
tokensLength = tokensLength + tokens.length;
inputLine = fileIn.readLine();
}
fileIn.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
//FULL ARRAY OF STRINGS IN TOKENZ
return tokenz;
}
public static String nextWord()
{
String[] tokenzz = readFile();
//????
return tokenzz[0];
}
}
Here's a conceptual model for you.
Keep track of your MyReader's state to know which value to return next.
the following example uses tokenIndex to decide where to read at next.
class MyReader
{
String[] tokens;
int tokenIndex = 0;
public String nextWord()
{
if(tokens == null || tokens.length <= tokenIndex)
{
// feel free to replace this line with whatever logic you want to
// use to fill in a new line.
tokens = readNextLine();
tokenIndex = 0;
}
String retVal = tokens[tokenIndex];
tokenIndex++;
return retval;
}
}
Mind you, this isn't a complete solution(it doesn't check for the end of file for instance), only a demonstration of the concept. You might have to elaborate a bit.
Use a loop and process each element in the array, printing them one at a time?

arrays and for loops

I wrote this code.
I am new to Java and willing to develop my skills,so I wrote this code,in order to learn Arrays,one developer suggested HashSet,I am looking forward for new suggestions.
import java.io.*;
public class dictionary
{
public static void main(String args[])
{
String[] MyArrayE=new String[5];
String[] MyArrayS=new String[5];
MyArrayE[0]="Language";
MyArrayE[1]="Computer";
MyArrayE[2]="Engineer";
MyArrayE[3]="Home";
MyArrayE[4]="Table";
MyArrayS[0]="Lingua";
MyArrayS[1]="Computador";
MyArrayS[2]="Ing.";
MyArrayS[3]="Casa";
MyArrayS[4]="Mesa";
System.out.println("Please enter a word");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word= null;
try {
word= br.readLine();
} catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Your word is " + word);
for(int i=0; i<MyArrayE.length; i++)
{
if(word.equals(MyArrayS[i]))
{
System.out.println(MyArrayE[i]);
}
}
}
}
My Question: What about if the user inputs a word not in MyArrayS, I want to check that and print a statement like "Word does not exist".
I think that it might look like:
if(word!=MyArrayS)
{
System.out.println("Word does not exist");
}
Thanks
You can simply use the .Contains(String) method to determine whether the word is contained within the array.
You have to check every element of the array to see that it's not there. So your code would actually look like:
int c;
boolean found = false;
for(c = 0;c < MyArrayS.length;c++) {
if(MyArrayS.compareTo(word) == 0) {
found = true;
}
}
if(!found) {
System.out.println("Word does not exist");
}

Categories