Heres my code. I'm not sure whats wrong. My project is to create a program that checks if a word is a palindrome.
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
// Open Scanner
Scanner input = new Scanner(System.in);
// Prompt User for word
System.out.println("Enter word to check if it is a Palindrome:");
// Scan in the word
String word = input.nextLine();
int a = 0; // used to extract word from array (small)
int b = 0; // used to extract word from array (large)
int c = 0; // used to stop when
int d = (word.length());
int e = d / 2;
int f = e - 2;
int x = word.length(); // set cap of array pulling
char[] array = word.toCharArray(); // create array of chars
if (array[a] == array[x] && c != f) {
a++;
x--;
c++;
} else {
b = 1;
}
if (b == 1) {
System.out.println("This word is not a Palindrome!");
} else if (b == 0) {
System.out.println("This word is a Palindrome!");
}
}
}
The error is at the
if (array[a] == array[x] && c!=f)
I'm not exactly sure what went wrong but when you put in a non-palindrome it skips over. I'd be more than glad to have some advice as to what to do in this situation.
Because arrays are 0-based, the index of the last entry is length -1.
int x = word.length() - 1
You are also missing a loop for checking all the characters in a word. And finally, you seem to have a lot of redundant variables. Here's how you could fix your code:
boolean isPalindrome = true;
for (int n = 0; n < array.length / 2; n++){
if (array[n] != array[array.length - n - 1]) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println("This word is a Palindrome!");
} else {
System.out.println("This word is not a Palindrome!");
}
Related
Learning Java at the minute. I’ve been asked to take an alphabetical string from user (can be any length/variation) assign a numeric value i.e. a=1, b=2 ....z=26 add the user input together using a recursive method. Not looking for a straight-out answer, just where I’ve gone wrong and a point in the right direction.
public static void main(String[] args) {
System.out.print("Enter a String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (int i = 0; i <= str.length() - 1; i++) {
int result = sumUp(i) + convertToNum(str.charAt(i));
System.out.print(result);
}
}
static int convertToNum(char userIn) {
int num = 0;
if (userIn >= 'a' && userIn <= 'z') {
num += 1 + userIn - 97;
}
return num;
}
static int sumUp(int n) {
if (n == 0)
return 0;
return (n % 10 + sumUp(n / 10));
}
I'm doing an assignment and I am done. This is a simple program that prints out pyramids of chars. However, I can't figure out why the program prints a newline when I never specified it with some input, even if it's meant to: https://i.imgur.com/gPs5oC5.png
Why do I have to have an extra newline when printing the pyramid upside down? Where is the newline printed?
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean state = true;
String messageL = "Length: ";
String messageD = "Position: ";
String messageS = "Shutdown!";
while(state) {
int limit = 0;
int degree;
System.out.print(messageL);
int length = input.nextInt();
while ((length < 1 && length == -1) || length > 26) {
if (length == -1 ) {
System.out.println(messageS + "\n");
state = false;
break;
} else {
System.out.print(messageL);
length = input.nextInt();
}
}
if (!state)
break;
System.out.print(messageD);
degree = input.nextInt();
while((degree > 1) || (degree < 0)) {
System.out.print(messageD);
degree = input.nextInt();
}
if (degree == 0)
//No newline is needed here for some reason.
length++;
else if (degree == 1)
limit = length;
//New line here for the pyramids to print symmetrically.
//System.out.println("");
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
System.out.print(letter);
}
if (degree == 0)
limit++;
else if (degree == 1)
limit--;
System.out.println("");
}
System.out.println("");
}
}
}
Small java program prints invisible newline?
In your program the last System.out.println(""); causes an extra line at the end of your program, i.e while(state) is true at the end, So either you comment the print statement or make your state=false at end.
while(state) {
...
System.out.println("");
}
The most inner loop won't run if the input is 0. limit will be 0, and hence the loop condition is false. As of this it will print en empty line, proceeding to add 1 too limit and then print chars.
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.
My current code
import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.contains("G")) {
G++;
} else {
if (S.contains("R")) {
R++;
} else {
if (S.contains("Y")) {
Y++;
} else {
if (S.contains("B")) {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G/total);
System.out.println(R/total);
System.out.println(Y/total);
System.out.println(B/total);
}
}
As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is
0.5
0.25
0.25
0.0
Any help would be appreciated!
The problem is that S.contains returns true if the whole string contains the given character. S.charAt should solve your problem:
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') G++;
else if (S.charAt(i) == 'R') R++;
else if (S.charAt(i) == 'Y') Y++;
else if (S.charAt(i) == 'B') B++;
}
Also, dividing integers will return an integer (rounded down). As such your output would always be 0 unless all the characters are the same. Just cast them to double before printing:
System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);
Edit: As pointed out by Sumit Gulati in a comment, a switch statement will have better performance in Java 7. Also, as David Conrad pointed out using only ifs in the for loop would work too as the conditions are mutually exclusive.
Your earlier code S.contains("some character") was finding the index of the character in the entire string. Use S.charAt(i) to specifically find the index at ith location in the string.
Finally, you need to convert the integer to floating point in order to print output as floating values.
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') {
G++;
} else {
if (S.charAt(i) == 'R') {
R++;
} else {
if (S.charAt(i) == 'Y') {
Y++;
} else {
if (S.charAt(i) == 'B') {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G * 1.0 / total);
System.out.println(R * 1.0 / total);
System.out.println(Y * 1.0 / total);
System.out.println(B * 1.0 / total);
}
}
Here is my analysis to this problem: There are four kinds of conditions where the brackets is matching: {{()}}, {}[]<>, <{}[]>, {<>[]}<>
So it could be complicated if I just think about these 4 matching forms. So I try to find out when is the brackets is not matching. if I let { and } be a pair, I find out if one bracket is on the odd position then his pair must be in a even position, vice versa. Take {<>[]}<> as an example, { is at the 1st position which is an odd position and } is at the 6th position which is an even position. Therefore I use numbers to mark them which '()'--1,9; '[]'--2,8; '<>' --3,7; '{}' --4,6 so if two number adds up is equals to 10 then these two numbers represents a pair. Then I use those numbers to represent bracket structure. and I pull out bracket in odd position and bracket in even position(use number to represent them) and I add each items in odd position and even position with each other to see if there is a match which adds up is 10, if not, I say it's a match. My code is as below:
/** Matching Brackets
* Tony
*/
import java.util.*;
public class Solution19 {
public static String process(String n) {
/** build a condition combination: */
String newString = "";
for (int i = 0; i < n.length(); i++) {
if (n.charAt(i) == '(' || n.charAt(i) == ')' || n.charAt(i) == '[' || n.charAt(i) == ']'
|| n.charAt(i) == '<' || n.charAt(i) == '>' || n.charAt(i) == '{' || n.charAt(i) == '}') {
newString += n.charAt(i);
}
}
return newString;
}
public static String numForm(String s) {
String newone = "";
for (int i = 0; i < s.length(); i++) {
switch(s.charAt(i)) {
case '(': newone += "1 ";break;
case ')': newone += "9 ";break;
case '[': newone += "2 ";break;
case ']': newone += "8 ";break;
case '<': newone += "3 ";break;
case '>': newone += "7 ";break;
case '{': newone += "4 ";break;
case '}': newone += "6 ";break;
}
}
return newone;
}
public static int[] intArray(String m) {
String[] stringArray = m.split(" ");
int[] intArr = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArr[i] = Integer.parseInt(stringArray[i]);
}
return intArr;
}
public static void printArray (int[] array) {
for (int n : array) {
System.out.print(n + " ");
}
}
public static int[] oddPosition (int[] array) {
int [] oddNumbers = new int[array.length / 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
if ((i + 1) % 2 != 0) {
oddNumbers[j] = array[i];
j ++;
}
}
return oddNumbers;
}
public static int[] evenPosition (int[] array) {
int [] evenNumbers = new int[array.length / 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
if ((i + 1) % 2 == 0) {
evenNumbers[j] = array[i];
j ++;
}
}
return evenNumbers;
}
public static boolean addsUpten (int [] array) {
boolean conditionSum = false;
boolean conditionSingle = false;
for (int i = 0; i < array.length; i++) {
int d = 0;
while (i + d < array.length) {
if (array[i] + array[i+d] == 10) {
conditionSingle = true;
}
conditionSum = (conditionSum || conditionSingle);
d ++;
}
}
return conditionSum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
String voider = sc.nextLine();
for (int i = 0; i < times; i ++) {
String formula = sc.nextLine();
String processed = process(formula);
String numFormed = numForm(processed);
// System.out.println(numFormed);
int[] numArray = intArray(numFormed);
if (numArray.length % 2 != 0) {
System.out.print("0 ");
}
else {
int[] oddNumbers = oddPosition(numArray);
int[] evenNumbers = evenPosition(numArray);
if (addsUpten(oddNumbers) || addsUpten(evenNumbers) == true) {
System.out.print("0 ");
}
else {
System.out.print("1 ");
}
}
}
}
}
as I expected, it should work and it does work when I input:
4
(a+[b*c]-{d/3})
(a + [b * c) - 17]
(((a * x) + [b] * y) + c
auf(zlo)men [gy<psy>] four{s}
it gives me output:1 0 0 1 (1 represent it is a match, 0 represent it's not a match). However when I input something longer like [^]<t>(z){<[^]<w>[{f}c]y[-][v]{<y>g<+( )>(c){w{a{t}}}}>((a)w)} it is a match but it gives me 0. I wonder the way I determine if it's a match or not is right or wrong? What did I miss? Sorry for the long code, just wondering ("I find out if one bracket is on the odd position then his pair must be in a even position, vice versa.") this way to describe a bracket match is right or wrong? Thx!
Your approach has a fundamental problem - it does not support nesting very well.
You can solve this by creating a stack of parentheses:
When you see an opening parenthesis, you push it on the stack
When you see a closing parenthesis, you pop an opening parenthesis that is supposed to pair with it off the stack
If the pair from the stack matches, continue
If the pair does not match, or the stack is empty, report a mismatch
If the stack is not empty at the end of the loop, also report a mismatch.
public class Palindrome
{
public static boolean isDoublePalindrome (char[] digits)
{
char[] firstHalf = new char[digits.length/2];
char[] secondHalf = new char[digits.length/2];
for(int a = 0; a < digits.length / 2; a++)
{
firstHalf[a] = digits[a];
System.out.print(firstHalf[a]);
}
for(int b = digits.length / 2; b < digits.length; b++)
{
secondHalf[b] = digits[b];
}
if(digits.length % 2 == 0)
{
for(int i = 0; i < digits.length / 2 - 1; i++)
{
if(digits[i] != digits[digits.length - i - 1])
{
return false;
}
else
{
return true;
}
}
for(int j = 0; j < firstHalf.length / 2 - 1; j++)
{
if(firstHalf[j] != firstHalf[digits.length - j - 1])
{
return false;
}
else
{
return true;
}
}
}
else if(digits.length % 2 != 0)
{
return false;
}
return false;
}
}
Here I take digits[] as parameter and whatever the character array in there I want to divide them into half and store first half into firstHalf and second half into secondHalf array. But when I debug, secondHalf doesn't have any values. Please help!!
method to do so
public int reverse(int num) {
int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;
}
implementation
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num = scanner.nextInt();
System.out.println("Please enter a string: ");
String str = scanner.next();
Palindrome palin = new Palindrome();
int revNum = palin.reverse(num);
if (num == revNum) {
System.out.printf("\n The number %d is a Palindrome ", num);
} else {
System.out.printf("\n The number %d is not a Palindrome ", num);
}
here palindrome is class name of main method hope my works helps you in this regard.
First off, be careful dividing your array length by 2, you may have an odd length (making one half 1 longer than the other).
What happens if "digits" is an odd number length? It can still be a palindrome.
To answer your question, in the second loop your assigning values to secondHalf[b], which is past it's length: "digits.length / 2". You should be assigning values into secondHalf[] starting at zero.
If you're lazy, this could be your way:
public static boolean isPalindrome(String s){
String reverse = new StringBuffer(s).reverse().toString();
if(s.equalsIgnoreCase(reverse))
return true;
else
return false;
}
And if you are not allowed to cheat, this could help you:
public static boolean isPalindrome(String s){
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length / 2; i++){
if(Character.toLowerCase(chars[i]) != Character.toLowerCase(chars[chars.length - 1 - i]))
return false;
}
return true;
}
EDIT: With the second version you also don't encounter the problem of overlooking a character, because if it is a odd number, it would be the middle character that both sides of the string share.