I'm trying to make a program that checks for palindromes(words spelt the same forwards and backwards). I want to eventually compare the first char with the last char and the second char with the second to last char. I don't know what to put in the 'endingChar' string to make it check for that. Thanks.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
String userPhrase;
Scanner sc = new Scanner(System. in );
System.out.println("Check for palindrome:");
userPhrase = sc.nextLine();
for (int i = 0; i < userPhrase.length(); i++) {
String currentChar = userPhrase.substring(i, i + 1);
String endingChar = userPhrase.substring();
System.out.println(currentChar);
System.out.println(endingChar);
// if (userPhrase.indexOf(currentChar).equalsIgnoreCase(userPhrase.indexOf()))
}
}
}
The simplest way to check for a palindrome would be to utilize StringBuilder.reverse():
boolean isPalindrome = userPhrase.equals(
new StringBuilder(userPhrase).reverse().toString());
System.out.printf("[%s] is a palindrome? %b", userPhrase, isPalindrome);
*Taken from Here, don't give me credit.
Here is some code for checking for a palindrome for integers. You could apply the logic to your code to make it work for strings as well:
// numbers to check
int numbers[] = new int[]{ 252, 54, 99, 1233, 66, 9876 };
// loop through the given numbers
for (int i = 0; i < numbers.length; i++) {
int numberToCheck = numbers[i];
int numberInReverse = 0;
int temp = 0;
// a number is a palindrome if the number is equal to it's reversed number
// reverse the number
while (numberToCheck > 0) {
temp = numberToCheck % 10;
numberToCheck = numberToCheck / 10;
numberInReverse = numberInReverse * 10 + temp;
}
if (numbers[i] == numberInReverse) {
System.out.println(numbers[i] + " is a palindrome");
}
else {
System.out.println(numbers[i] + " is NOT a palindrome");
}
You could rather use this
for(int i=0;;i++)
{
if(i>=userPhrase.length-i)
break;
if(userPhrase.charAt(i)==userPhrase.charAt(userPhrase.length-i))
{
continue;
}
System.out.println("Not matched");
}
Related
I have to reverse the string a user inputs and I'm trying to remove the negative sign when a user enters a negative number but I'm unsure of how to go about this.
I've tried using string.replace() but I instead of printing for example "9" when a user entered "-9", it would return "99-9"
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
System.out.println("Type a number: ");
String num = scnr.nextLine();
String reverse = "";
for (int i = num.length() - 1; i >= 0; i--) {
reverse = reverse + num.charAt(i);
}
System.out.println("Reverse is: " + reverse);
}
}
The straight forward solution: put an if block in your loop!
You are right now adding characters unconditionally. You could for example only append characters that are digits. Then any other thing, like a '-' won't show up in your output!
You can try something like this.
public class App {
public static void main(String[] args) {
String input = "78-889-969-*)(963====";
StringBuilder builder = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
if (input.charAt(i) >= 48 && input.charAt(i) <= 57) {
builder.append(input.charAt(i));
}
}
System.out.println("builder = " + builder.toString());
}
}
Using Character.isDigit()
public class App {
public static void main(String[] args) {
String input = "78-889-969-*)(963====";
StringBuilder builder = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
if (Character.isDigit(input.charAt(i))) {
builder.append(input.charAt(i));
}
}
System.out.println("builder = " + builder.toString());
}
}
Replace the for loop with the below.
for (int i = num.length() - 1; i >= 0; i--)
{
if(num.charAt(i) == 45){
break;
}
reverse = reverse + num.charAt(i);
}`
45 is the ASCII value of - sign. The if(num.charAt(i) == 45) checks if there is - sign and if so it breaks the loop before it prints the - sign.
Note - The loop will not break till it reaches i = 0.
I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input
I am trying to convert the input of a Int directly to a String.
I am also trying to make it so the program will find the correct number in a credit card sequence to make it correct.
For example if I input a incorrect credit card number, the program finds a way to change the numbers so it becomes correct.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input a credit card number to validate");
String cc = in.nextLine();
validateCreditCardNumber(cc);
String convertedCC = (cc);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
That is all my code, but what i am trying to fix is when I initialize cc, i can convert to a string to be later used.
My issues:
int to string has been fixed,
converting to correct CC number has not been fixed.
Can you just get it as a string directly?
String cc = in.nextLine();
Use following code instead of int cc = in.nextInt();
String cc = in.next();
You never use the int version of the scanned input. Instead of making cc an int then converting to a string, just initially make it a string... something like this:
String cc = in.nextLine();
Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}
I'm scanning 2 strings during each iteration and storing it in s and t. Only during the first iteration, the first string that I scan is getting stored in t and not in s (I got to know this by debugging in eclipse). During successive iterations the piece of code works fine. I'm not able to understand what is going on during the first iteration. Please help me. Thanks.
import java.io.*;
import java.util.*;
public class ResidentInfo {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int i,n;
n = scan.nextInt();
for(i=0 ; i<n ; i++)
{
int sl,tl,j,k;
String s, t;
boolean flag = false;
s = scan.nextLine();
t = scan.nextLine();
sl = s.length();
tl = t.length();
char[] sa = new char[sl];
char[] ta = new char[tl];
sa = s.toCharArray();
ta = t.toCharArray();
for(j=0 ; j<sl ; j++)
{
for(k=0 ; k<tl ; k++)
{
if(sa[j]==ta[k])
{
flag = true;
break;
}
}
if(flag)
{
break;
}
}
if(flag)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
The first thing this code does is determine if the two strings' lengths are equal. If the strings' lengths are not equal, the code prints no. If the lengths are equal, the code then checks each character in the exact same index in the strings, to see if they are equal. If the characters at a specific index is not equal, the code breaks the loop and prints no. If all of the characters at each index are equal the code prints yes.
You asked a question about next() and nextLine().
Try: Question asked already.
Scanner scan = new Scanner(System.in);
System.out.print("enter a number: ");
int n = scan.nextInt();
for(int i=0; i < n; i++)
{
boolean flag = true;
System.out.print("enter something for s: ");
String s = scan.next();
System.out.print("enter something for t: ");
String t = scan.next();
if(s.length() == t.length())
{
for(int j = 0; j < s.length(); j++)
{
if(s.charAt(j) != t.charAt(j))
{
flag = false;
break;
}
}
if(flag)
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}
}
else
{
System.out.println("NO");
}