I`m Study Java, But I found a problem in javatutorials.
/* ContinueWithLabelDemo.java */
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
When i Debuging this program, I found something wried in its class file:
/* ContinueWithLabelDemo.class */
class ContinueWithLabelDemo {
ContinueWithLabelDemo() {
}
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
label26:
for(int i = 0; i <= max; ++i) {
int n = substring.length();
int j = i;
int k = 0;
do {
if(n-- == 0) {
foundIt = true;
break label26;
}
} while(searchMe.charAt(j++) == substring.charAt(k++));
}
System.out.println(foundIt?"Found it":"Didn\'t find it");
}
}
The while loop become do/while loop. So i replace code from *.class to *.java and build it again.now the do/while loop become while loop. Is there necessary exchange them every build? why Java do this?
Related
I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}
I am working on a Four in a row game.
But I have run into a problem with it. I have been able to make the game work. But I would like to know if I can move my public void fillBoard() and public void presentBoard() into another class. This is because I would like to make the code more organised.
package com.company;
public class Main {
public static void main(String[] args)
{
GameMechanics game = new GameMechanics();
game.play();
}
}
package com.company;
import java.util.Scanner;
public class GameMechanics
{
/*
This is my local variables
*/
public Scanner scanner = new Scanner(System.in);
public char token;
public int column;
public int player = 2;
public int turn = 2;
public int count = 0;
public boolean gameRunning = true;
public void play()
{
this.createBoard();
//While gameRunning is true, the methods inside the { } will run, and that's the 4InARow game
while (gameRunning)
{
this.presentBoard();
this.changeTurn();
this.dropToken();
this.gameWon();
}
presentBoard();
}
public void gameWon()
{
this.winConHorizontal();
this.winConVertical();
}
private char[][] board = new char[6][7];
//Creating my board and assign "space" to all the fields in the array.
public void createBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
//Presents the board, it prints the board with |"space"| so it looks more like a gameboard.
public void presentBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (j == 0) {
System.out.print("|");
}
System.out.print(board[i][j] + "|");
}
System.out.println();
}
}
public void changeTurn() {
if (this.turn == this.player) {
this.turn = 1;
this.token = 'X';
} else {
this.turn++;
this.token = 'O';
}
}
public void dropToken() {
System.out.println("player " + turn + ": press 1-7 to drop the token");
column = scanner.nextInt() - 1;
//If pressed any intValue outside the board, it will tell you to try again.
if (column >= 7 || column <= -1)
{
System.out.println("place the token inside the bord");
changeTurn();
} else {
//Drops the token and replace it with playerChar.
for (int i = 5; i > -1; i--) {
if (board[i][column] == ' ')
{
board[i][column] = token;
break;
}
}
}
}
public boolean winConHorizontal() {
while (gameRunning) {
for (int i = 0; 6 > i; i ++) {
for (int j = 0; 7 > j; j ++) {
if (board[i][j] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
public boolean winConVertical() {
while (gameRunning) {
for (int i = 0; 7 > i; i ++) {
for (int j = 0; 6 > j; j ++) {
if (board[j][i] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
}
An easy way to do this is as follows:
extract your char[][] board into its own class, e.g. Board
Said class could expose the function char getField(int index)
Extract the ,,presenting" part of your code into another class, e.g. BoardPresenter. Said class should have a function presentBoard(Board board) which internally uses getField(int index) of the Board class.
By doing this you abstract away your internal board storage mechanism while also reducing the number of responsibilities the GameMechanics class has (See https://en.wikipedia.org/wiki/Single_responsibility_principle)
yes, you can make another class and extend it with the current class GameMechanics and inside another class you can define the functions.
Note : This is a very simple approachable way.
Otherwise better if you manage your classes and interfaces similar to mvc model, for which you can search youtube for mvc structure java.
import java.util.Scanner;
public class StringWithoutDuplicate {
public static void stringWithoutDuplicate(String s1)
{
int n = s1.length();
int i = 0;
while(i<n)
{
if(s1.charAt(i) == s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
i++;
}
else if(s1.charAt(i) != s1.charAt(i+1))
{
if(s1.charAt(i) == s1.charAt(n-1))
{
System.out.println(s1.charAt(i));
}
System.out.println(s1.charAt(i));;
i++;
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter(",");
String s1 = s.next();
System.out.println(s1);
stringWithoutDuplicate(s1);
}
}
The code is giving the output but with an exception
please tell me the error in my code and ways to correct it.
I don't want to change the logic of my code so kindly solve it using this logic only.
ERROR:
Range of your i is from 0 to (n-1) which is same as the range of index of characters in your string s1. This is correct.
But during the last iteration of your while loop, i = n-1
At this point, s1.charAt(i+1) becomes same as s1.charAt(n). This should be giving an error.
public static void stringWithoutDuplicate(String s1) {
int prev = -1;
for (int i = 0, size = s1.length(); i < size; ++i) {
char c = s1.charAt(i);
if (c != prev) {
System.out.println(c);
prev = c;
}
}
}
Problem:
Develop a recursive algorithm to determine if there is a palindrome hidden within a longer word or phrase. A palindrome is a word or phrase that has the same sequence of letters when read from left to right and when read from right to left, ignoring the spaces (e.g., Some like cake, but I prefer pie contains the palindrome I prefer pi).
Below is my code:
public class e125 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i = 0;
String sLine = "Some like cake, but I prefer pie";
sLine.replaceAll("\\s+", "");
System.out.println(PlainRet(sLine, i));
}
public static String PlainRet(String sLine, int i) {
int nNum;
char c = 0;
String sPlain = "";
if (i >= sLine.length()) {
return "No Plaindrome";
}
c = sLine.charAt(i);
nNum = Isgood(sLine, c, i);
if (nNum != 0) {
for (; i < nNum; i++) {
sPlain += sLine.charAt(i);
}
return sPlain;
}
return PlainRet(sLine, i + 1);
}
public static int Isgood(String sLine, char c, int i) {
for (int j = i + 1; j < sLine.length(); j++) {
if (Character.toUpperCase(sLine.charAt(j)) == Character.toUpperCase(c)) {
if (Isplain(sLine, i, j)) {
return j;
}
}
}
return 0;
}
public static boolean Isplain(String sLine, int i, int j) {
if (Character.toUpperCase(sLine.charAt(j)) != Character.toUpperCase(sLine.charAt(i))) {
return false;
}
else if (i == j || j == i + 1) {
return true;
}
return (Isplain(sLine, i + 1, j - 1));
}
}
I keep getting an output of "I"
I have no idea what is wrong.
Like FatalError commented sLine.replaceAll() returns a new String. You need to reassign sLine or pass the results of the replaceAll() into the method.
You'll find a new error to fix after you do that, but it's just an off-by-one!
I'm trying to implement KMP algorithm. My algorithm works correctly with the following example
Text: 121121
Pattern: 121
Result: 1,4
But when Text is 12121 and pattern is the same as above, result just: 1. I don't know if this is the problem of the algorithm or of my implementation?
Other example:
Text: 1111111111
Pattern: 111
Result: 1,4,7
My code is:
public class KMP {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = reader.readLine();
String pattern = reader.readLine();
search(text,pattern);
}
private static void search(String text,String pattern)
{
int[] Pi = Pi(pattern);
for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
while (q>=0 && pattern.charAt(q)!=text.charAt(i))
{
q=Pi[q];
}
if(q==pattern.length()-1) {
System.out.println(i-pattern.length()+2);
q=Pi[q];
}
}
}
private static int[] Pi(String p) {
int[] Pi = new int[p.length()];
Pi[0]=-1;
int i=0;
int j=-1;
while (i<p.length()-1) {
while (j>=0 && p.charAt(j)!=p.charAt(i))
{
j=Pi[j];
}
i++;
j++;
if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
else Pi[i]=j;
}
return Pi;
}
}
Hope help you.
public int strStr(String source, String target) {
if (source == null || target == null){
return -1;
}
if (source.isEmpty() && !target.isEmpty()){
return -1;
}
if (source.isEmpty() && target.isEmpty()){
return 0;
}
if (target.isEmpty()){
return 0;
}
int index = 0;
int compare_index = 0;
int compare_start_index = 0;
int compare_same_length = 0;
List<Integer> answers = new ArrayList<Integer>();
while (true){
if (compare_same_length ==0){
compare_start_index = compare_index;
}
if (source.charAt(compare_index) == target.charAt(index)){
compare_same_length++;
index++;
} else {
if (compare_same_length >0){
compare_index--;
}
compare_same_length = 0;
index = 0;
}
compare_index++;
if (compare_same_length == target.length()){
answers.add(compare_start_index+1);
compare_same_length=0;
index=0;
}
if (compare_index == source.length()){
//here are answers
for (int i = 0; i < answers.size(); i++) {
int value = answers.get(i);
}
return 1;
}
}
}