I am new to java, and have been writing a program to check if a given string is periodic or not.A string is not periodic if it cannot be represented as a smaller string concatenated some number of times. Example "1010" is periodic but "1011" is not. Here is my code. It compiles, but the problem is that it tells every string is not periodic. I guess the problem is with the for loop in the isPeriodic function. Please help me get it correct.
import java.io.*;
import java.util.*;
public class Test {
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader R = new java.io.BufferedReader
(new java.io.InputStreamReader(System.in));
//String st = R.readLine();
String st = "10101010";
if (isPeriodic(st) == false) {
System.out.println(" Non Periodic");
}
else {
System.out.println("Periodic");
}
}
private static boolean isPeriodic(String s)
{
String temp = s;
int i;
boolean pflag = false;
for ( i = 1; i <= (s.length()/2); i++) {
s = rotateNltr(s,i);
if (s == temp) {
pflag = true;
break;
}
}
return pflag;
}
private static String rotateNltr(String s, int n) {
if( n > s.length()) {
return null;
}
for ( int i = 0; i < n; i++) {
s = leftRotatebyOne(s);
}
//System.out.println(s);
return s;
}
private static String leftRotatebyOne(String s) {
char[] temp = s.toCharArray();
char t = temp[0];
for ( int i = 0 ; i < s.length()-1 ;i++ ) {
temp[i] = temp [i+1];
}
temp[s.length()-1] = t;
String r = new String(temp);
//System.out.println(r);
return r;
}
}
You can't compare objects (and that includes String's) with ==. You have to use the equals method.
Unlike C++ (which I assume is your language of preference) Java doesn't allow comparing String objects with the == operator. Use the equals method to compare the strings.
if (s.equals(temp)) {
pflag = true;
break;
}
In your isPeriodic() the check you are doing is wrong. Do it as below:
if (s.equals(temp)) {
pflag = true;
break;
}
s.equal(temp) alone wont solve the problem, yes it will make the code execute correctly for the input as given in Main method but for 1010, 1011 it wont.
Try using this method :
private static boolean isPeriodic(String s) {
String temp = s;
int i;
boolean pflag = false;
for (i = 1; i <= (s.length() / 2); i++) {
s = leftRotatebyOne(s);
if (s.equals(temp)) {
pflag = true;
break;
}
}
return pflag;
}
This will ensure that for all combination this program works.
Related
public class Test {
public static String MakeSequence(int N)
{
int j;
N=5;
for (N=5;N>=1;--N)
{
for(j=1;j<N+1;++j)
{
return MakeSequence(5);
}
}
if (N<1)
{
String x = "";
System.out.println(x.isEmpty());
}
}
}
I want to return the sequence 555554444333221 when N=5 and return an empty string if the input parameter N is less than 1, but I'm not sure how to modify the code I made
Be simple and do not add additional checks:
public static String makeSequence(int N) {
StringBuilder buf = new StringBuilder();
while (N > 0) {
buf.append(String.valueOf(N).repeat(N));
N--;
}
return buf.toString();
}
public class Test {
public static String makeSequence(int n) {
String value = " ";
for (int i = n; i >= 1; --i) {
for (int j = 1; j < i + 1; ++j) {
value+= i;
}
}
return value;
}
public static void main(String[] args) {
final String s = makeSequence(5);
System.out.println(s);
}
}
In your code, you always try to assign 5 instead of considering the value send to the method. Above solution returns the sequence and if the parameter N(in code I use n) is less than 1 then returns the empty string.
FYI: As a best practice we start both variable and method names in simple letters.
public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
Output: true
So does toUpperCase() always create a new object?
toUpperCase() calls toUpperCase(Locale.getDefault()), which creates a new String object only if it has to. If the input String is already in upper case, it returns the input String.
This seems to be an implementation detail, though. I didn't find it mentioned in the Javadoc.
Here's an implementation:
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR)
|| (c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this; // <-- the original String is returned
}
....
}
I asked a question yesterday about palindromes and Java:
Java Palindrome Program (am I on track)?
I've made some progress so far with all your help (thank you very much again). I just need help with one more thing before I can test the code out. I'm using Eclipse and I'm getting an error on one line (I'll also include the error as a comment in the code below). I keep getting a "Cannot invoke charAt(int) on the array type String[]".
Anyone know what is going on here? It's been a while since I used Java. Used it in C.S. One about 12 months ago, then I moved on to C++ in Data Structures, then Machine Code and Assembly Language in the next course. Here's the code (I've also included the error in a comment in the code). Thanks a lot:
public class Palindrome
{
public boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] theWord )
{
int leftPointer = 0;
int rightPointer = theWord.length - 1;
for ( int i = 0; i < theWord.length / 2; i++ ) {
while (leftPointer >= rightPointer) {
if ( theWord.charAt(i) == theWord.charAt (theWord.length - i - 1) ) { // Error: Cannot invoke charAt(int) on the array type String[]
leftPointer++;
rightPointer--;
}
System.out.println(theWord);
}
}
}
}
You are trying to access a charAt() on an String[] (A String array of the arguments passed to your program), but you need to access it on a String. I world suggest something like:
if ( theWord[i].charAt(0) == theWord[theWord.length - i - 1].charAt (0) ) {
That might help you.
charAt(int index) is applied for a String, not a String array. Your program want to decide whether a string is a palindrome, like "abcba". Instead of check whether an array of Strings are all palindrome, right? For example {"abcba", "bbc", "aba"}.
In Java (as in C++) the program received parameter list, which is the array of Strings. Thus your class should looks like below:
public class Palindrome
{
public static boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] args )
{
String theWord = args[0]; // first word passed to the program
boolean isPalindrom = Palindrome.isPalindrome(theWord);
System.out.println(theWord + " is" + ( isPalindrom ? "" : " NOT " ) + " a Palindrome." );
}
}
You forgot the () after invoking the method .length()
public static boolean isPalindrom(String value) {
if (value == null || value.length()==0 || value.length()==1) {
return true;
}
if(value.charAt(0)!=value.charAt(value.length()-1)) {
return false;
}
StringBuilder newValue =new StringBuilder(value);
newValue = new StringBuilder(newValue.substring(1, newValue.length()));
newValue = new StringBuilder(newValue.substring(0, newValue.length()-1));
return isPalindrom(newValue.toString());
}
try this simple recursive method.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str = "pappap";
String sp = str.toLowerCase();
char[] ch = sp.toCharArray();
int len = ch.length;
int lastIndex = ch.length-1;
int count = 1;
int first = 0;
int last = sp.length()-1;
for(; first < last ;){
if(ch[first] == ch[last] ){
first= first+1;
last= last-1;
}
else{
count = 0;
break;
}
}
String result = (count == 1) ? "Palindrome" : "Not a palindrome " ;
System.out.println(result);
}
}
This question already has an answer here:
Counting distinct words with Threads
(1 answer)
Closed 9 years ago.
I've asked this question before ( Counting distinct words with Threads ) and made the code more appropriate. As described in first question I need to count the distinct words from a file.
De-Bug shows that all my words are stored and sorted correctly, but the issue now is an infinite "while" loop in the Test class that keeps on going after reading all the words (De-bug really helped to figure out some points...).
I'm testing the code on a small file now with no more than 10 words.
DataSet class has been modified mostly.
I need some advice how to get out of the loop.
Test looks like this:
package test;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import junit.framework.TestCase;
import main.DataSet;
import main.WordReader;
public class Test extends TestCase
{
public void test2() throws IOException
{
File words = new File("resources" + File.separator + "test2.txt");
if (!words.exists())
{
System.out.println("File [" + words.getAbsolutePath()
+ "] does not exist");
Assert.fail();
}
WordReader wr = new WordReader(words);
DataSet ds = new DataSet();
String nextWord = wr.readNext();
// This is the loop
while (nextWord != "" && nextWord != null)
{
if (!ds.member(nextWord))
{
ds.insert(nextWord);
}
nextWord = wr.readNext();
}
wr.close();
System.out.println(ds.toString());
System.out.println(words.toString() + " contains " + ds.getLength()
+ " distinct words");
}
}
Here is my updated DataSet class, especially member() method, I'm still not sure about it because at some point I used to get a NullPointerExeption (don't know why...):
package main;
import sort.Sort;
public class DataSet
{
private String[] data;
private static final int DEFAULT_VALUE = 200;
private int nextIndex;
private Sort bubble;
public DataSet(int initialCapacity)
{
data = new String[initialCapacity];
nextIndex = 0;
bubble = new Sort();
}
public DataSet()
{
this(DEFAULT_VALUE);
nextIndex = 0;
bubble = new Sort();
}
public void insert(String value)
{
if (nextIndex < data.length)
{
data[nextIndex] = value;
nextIndex++;
bubble.bubble_sort(data, nextIndex);
}
else
{
expandCapacity();
insert(value);
}
}
public int getLength()
{
return nextIndex + 1;
}
public boolean member(String value)
{
for (int i = 0; i < data.length; i++)
{
if (data[i] != null && nextIndex != 10)
{
if (data[i].equals(value))
return true;
}
}
return false;
}
private void expandCapacity()
{
String[] larger = new String[data.length * 2];
for (int i = 0; i < data.length; i++)
{
data = larger;
}
}
}
WordReader class didn't change much. ArrayList was replaced with simple array, storing method also has been modified:
package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class WordReader
{
private File file;
private String[] words;
private int nextFreeIndex;
private BufferedReader in;
private int DEFAULT_SIZE = 200;
private String word;
public WordReader(File file) throws IOException
{
words = new String[DEFAULT_SIZE];
in = new BufferedReader(new FileReader(file));
nextFreeIndex = 0;
}
public void expand()
{
String[] newArray = new String[words.length * 2];
// System.arraycopy(words, 0, newArray, 0, words.length);
for (int i = 0; i < words.length; i++)
newArray[i] = words[i];
words = newArray;
}
public void read() throws IOException
{
}
public String readNext() throws IOException
{
char nextCharacter = (char) in.read();
while (in.ready())
{
while (isWhiteSpace(nextCharacter) || !isCharacter(nextCharacter))
{
// word = "";
nextCharacter = (char) in.read();
if (!in.ready())
{
break;
}
}
word = "";
while (isCharacter(nextCharacter))
{
word += nextCharacter;
nextCharacter = (char) in.read();
}
storeWord(word);
return word;
}
return word;
}
private void storeWord(String word)
{
if (nextFreeIndex < words.length)
{
words[nextFreeIndex] = word;
nextFreeIndex++;
}
else
{
expand();
storeWord(word);
}
}
private boolean isWhiteSpace(char next)
{
if ((next == ' ') || (next == '\t') || (next == '\n'))
{
return true;
}
return false;
}
private boolean isCharacter(char next)
{
if ((next >= 'a') && (next <= 'z'))
{
return true;
}
if ((next >= 'A') && (next <= 'Z'))
{
return true;
}
return false;
}
public boolean fileExists()
{
return file.exists();
}
public boolean fileReadable()
{
return file.canRead();
}
public Object wordsLength()
{
return words.length;
}
public void close() throws IOException
{
in.close();
}
public String[] getWords()
{
return words;
}
}
And Bubble Sort class for has been changed for strings:
package sort;
public class Sort
{
public void bubble_sort(String a[], int length)
{
for (int j = 0; j < length; j++)
{
for (int i = j + 1; i < length; i++)
{
if (a[i].compareTo(a[j]) < 0)
{
String t = a[j];
a[j] = a[i];
a[i] = t;
}
}
}
}
}
I suppose the method that actually blocks is the WordReader.readNext(). My suggestion there is that you use Scanner instead of BufferedReader, it is more suitable for parsing a file into words.
Your readNext() method could be redone as such (where scan is a Scanner):
public String readNext() {
if (scan.hasNext()) {
String word = scan.next();
if (!word.matches("[A-Za-z]+"))
word = "";
storeWord(word);
return word;
}
return null;
}
This will have the same functionality as your code (without using isCharacter() or isWhitespace() - the regex (inside matches())checks that a word contains only characters. The isWhitespace() functionality is built-in in next() method which separates words. The added functionality is that it returns null when there are no more words in the file.
You'll have to change your while-loop in Test class for this to work properly or you will get a NullPointerException - just switch the two conditions in the loop definition (always check for null before, or the first will give a NPE either way and the null-check is useless).
To make a Scanner, you can use a BufferedReader as a parameter or the File directly as well, as such:
Scanner scan = new Scanner(file);
I am new here and in programming as well. I am trying to study other topics alone since my instructor isn't enough help when I have a question so here it goes. I want reverse a word with a generic Stack.
My pop,push,isEmpty and peek methods work (I tested them with a simpler program I made before I tried it on this one.) and the output seems to be giving me the reversed word char by char but always giving me a null before each char!
My questions are:
Why is this happening? And even though I have an expandCapacity method to work when the capacity is at 9 but it doesn't apply when the input passes the limit.
Here's my code
package Stack;
import java.util.Scanner;
public class ReverseDriver<T> {
private static String out;
private static String in;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
in = input.nextLine();
int size = in.length();
ArrayStack<Character> revStack = new ArrayStack<>(size);
for (int i = 0; i < in.length(); i++) {
char u = in.charAt(i);
revStack.Push(u);
if (in.length() > 9) {
revStack.expandCapacity();
}
}
while (!revStack.IsEmpty()) {
char u = revStack.Pop();
out = out + u;
System.out.flush();
System.out.print(out);
}
}
}
Here's the Output
run:
Enter a word:
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
EDIT: here's the methods that I said that were working.
#Override
public void Push ( T element)
{
if (count == stack.length){
expandCapacity();
}
stack[++count] = element;
//System.out.println(count);
}
#Override
public String toString()
{
String result = "<top of stack>\n";
for (int index=count-1; index >= 0; index--){
result += stack[index] + "\n";
}
return result + "<bottom of stack>";
}
#Override
public boolean IsEmpty()
{ //Checks if array is empty
if(count == 0){
System.out.println("Nothing");
}
return count == 0;
}
public T Pop()
{
T output;
output = (stack[count - 1]);
count--;
return(output);
}
#Override
public T Peek()
{
//looks at the object at the top of this stack without removing it
//from the stack.
if(stack.length == 0){
// {
System.out.println("Cant peek a ghost");
}
return(stack[--count]);
}
// else
// {
// System.out.println( stack[count-1]);
// }
// }
#Override
public int Size()
{
//Sets the size of this vector
if(stack.length == 0){
System.out.println("Nothing inside");
}
System.out.println("The array's size is : " + count);
return count;
}
}
private static String out;
The value in out is null.
out = out + u;
// This is null = null + u;
Hence the null at the beginning of your output.
You simply need to create a new String object to give out an initial value:
private static String out = "";
i'm not sure why you need the ExpandCapacity bit there, this works aswell:
public static void main(String[] args)
{
String word ="reverse please";
Stack<Character> chStack = new Stack<Character>();
for (int i = 0; i < word.length(); i ++)
{
chStack.push(word.charAt(i));
}
String out = "";
while (chStack.size() != 0)
{
out += chStack.pop();
System.out.println(out);
}
}
There are a few notes:
You are not writing a generic class so drop .
Leave the iteration to for as much as possible.
Try using Java standard classes as much as possible, in this case Stack instead of ArrayStack.
You don't need to resize the stack, it will handle its size dynamically as you put more data in.
You should write the string once you are done creating it not once in every step.
Appending strings using + is very inefficient. Use StringBuilder.
Use methods they make your code readable.
Heres the code:
import java.util.Scanner;
import java.util.Stack;
public class ReverseDriver {
public static String reverse(String string) {
Stack<Character> revStack = new Stack<Character>();
for (char c : string.toCharArray()) {
revStack.push(c);
}
StringBuilder builder = new StringBuilder();
while(!revStack.isEmpty()){
builder.append(revStack.pop());
}
return builder.toString();
}
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
String in = input.nextLine();
System.out.println(reverse(in));
}
}