how to replace an integer array with characters in java - java

int = 0111254
replace all 0 with 'z'
replace odd integers with 'p'
replace even integers with 'q'
The output should be zpppqpq
My part of the code....
public static void main(String[] args) {
int num;
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
int temp;
int b[]=new int[10];
char a[]=new char[10];
for(int i=0;i<b.length;i++) {
while(num!=0)
{
temp=num%10;
b[i]=temp;
num=num/10;
}
}
for(int i=0;i<b.length;i=i+2)
{
if(b[i]==0)
{
b[i]=115;
}
else if(b[i]%2!=0)
{
b[i]=113;
}
else if(b[i]%2==0) {
b[i]=112;
}
}
for(int i=0;i<a.length;i++)
{
a[i]=(char)b[i];
}
for(int i:a)
{
System.out.print((char)i);
}
it gives a wrong output of q s s s s

You could turn that integer into a string and then use String.replace().
String numberString = ""+0111254;
// Replace all 0 chars with z
numberString.replace('0','z');
// etc...

you can take the numbers into a string and then convert strings into an array, and by using a for loop, take the single number and parse into integer, then apply your logic.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ary = String.valueOf(sc.next()).split("");
StringBuilder answer = new StringBuilder();
for (String n : ary) {
int value = Integer.parseInt(n);
if (value == 0) {
answer.append("z");
} else if (value % 2 == 0) {
answer.append("q");
} else {
answer.append("p");
}
}
System.out.print(answer.toString());
}

Related

Problem with Java code that will print TRUE when a word has no vowels in an IF statement

I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}

Way too long words

This is my solution to the "way too long words" problem on codeforces.
Even though I am getting correct output, but still it has been reported as the wrong answer to a question by codeforces.
https://codeforces.com/problemset/problem/71/A
(link to the question)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//charAt() is an inbuilt method which can read a string letter by letter
Scanner input=new Scanner(System.in);
int n;
//System.out.println("how many words do you wish to enter?");
n=input.nextInt();
String[] words=new String[n+1];
for(int i=0;i<n+1;i++)
{
words[i]=input.nextLine();
}
for(int j=0;j<n+1;j++)
{
if(words[j].length()<10)
{
System.out.print(words[j]);
}
else
{
System.out.print(words[j].charAt(0));
System.out.print(words[j].length()-2);
System.out.print(words[j].charAt(words[j].length()-1));
}
System.out.print("\n");
}
}
}
Problem is with the condition, you are only skipping words below the length of 10 but not considering the words with exact of 10 length.
if(words[j].length()<=10)
{
System.out.print(words[j]);
}
Change the condition it should work.
Inside the for loop for int j do something like this -
if(words[j].length()<=10) //boundary check
{
System.out.print(words[j]);
}
else
{
System.out.println(words[j].charAt(0).toString() + words[j].length()-2 + words[j].charAt(words[j].length()-1).toString());
}
Because where r you entering string in your program. Once you run, you will get to know.
Btw this is the solution of actual problem.
public static void main(String[] args){
String str=null;
int count=0;
Scanner scanner= new Scanner(System.in);
System.out.println("enter string :");
str=scanner.nextLine();
for(int i=0; i<str.length(); i++) {
count ++;
}
char first=str.charAt(0);
char last=str.charAt(count-1);
int num=count-2;
System.out.println("abbreviation is :" +first+num+last);
}
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string change_abb(string str)
{
string result;
if(str.length()>10)
{
int k=str.length()-2;
stringstream ss;
ss<<k;
string s;
ss>>s;
result+=str[0];
result+=s;
result+=str[str.length()-1];
}
else
{
result=str;
}
return result;
}
int main()
{
string in_str;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>in_str;
cout<<change_abb(in_str)<<endl;
}
}
Here is my answer in Python 3 (Answer accepted by Codeforces)
n = int(input())
p=""
for i in range(n):
s = input()
if len(s)>10:
p = s[0]+str((len(s)-2))+s[len(s)-1]
else:
p=s
print(p)

My array keeps on printing out zeroes and I don't know why

import java.util.Scanner;
import java.io.*;
public class practice3
{
public static void main(String[] args) throws IOException
{
int[] array = new int [99];
array = inputData();
for(int i=0; i<array.length; i++)
System.out.printf("%d",array[i]);
}
public static int[] inputData() throws IOException
{
final int MAX= 100;
int[] nums = new int[MAX];
int count = 0;
Scanner kb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String input = kb.nextLine();
File file = new File(input);
if(!file.exists())
{
System.out.println("The file entered is not found");
System.exit(0);
}
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && count < nums.length)
{
nums[count] = inputFile.nextInt();
count++;
}
inputFile.close();
return nums;
}
public static void printArray(int[] array, int counter)
{
System.out.println("Original array: ");
System.out.printf("%,12\n", array);
}
}
I don't know why these zeroes are printed after the array values I test from opening a file. I want to print the array itself and not the rest of the numbers. I tried messing with the MAX variable, but I dont know what to do.
The for loop in you main() iterates over the length of the array, which is 100 elements. The elements that you did not overwrite default to 0.
To solve this, pass the array as an argument to your inputData() and have it return how many elements it put into the array like:
public static int inputData(int[] input) {
// ...
input[count] = whatever;
// ...
return count;
}
Refactor arrays from int to Integer (0 -> null)
Add this before printing, it'll remove nulls from Integer (not int) array. (if int there will be zeroProblem)
int count = 0;
for (Integer i : array) {
if (i != null) {
count++;
}
}
Integer[] newArray = new Integer[count];
int index = 0;
for (Integer i : array) {
if (i != null) {
newArray[index++] = i;
}
}

How to solve this java.lang.NumberFormatException in palindrome?

I dont know why it won't work... I've tried changing it from int to long... The last input 46894 causes a problem... Help me please.
Here is my code:
import java.util.*;
public class palimdrone
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] number = new int[12];
int input = scan.nextInt();
for(int x=0;x<input;x++)
{
number[x] = scan.nextInt();
}
for(int a=0;a<input;a++)
{
long tot =0,sumA=0,sumB=0,attempt=0;
sumA = number[a];sumB=reverse(number[a]);
boolean palin=false;
if(sumA==sumB)
{
palin = true;
attempt++;
}
else
{
while(attempt!=10)
{
attempt++;
tot = sumA+sumB;
if(tot == reverse(tot))
{
palin=true;
break;
}
sumA=tot;
sumB=reverse(tot);
}
}
if(palin==true)
System.out.println(tot+" is Palindrome ; Attempt: "+attempt);
else
System.out.println(tot+"; None");
}
}
public static long reverse(long num)
{
String tnum=""+num;
String reverse="";
for(int x=tnum.length()-1;x>=0;x--)
{
reverse = reverse+tnum.charAt(x);
}
num = Integer.parseInt(reverse);
return num;
}
}
Here's the input
87<br>
196<br>
1689<br>
46785<br>
46894 <-- Error Here<br><br>
Here's the output
4884 is Palindrome ; Attempt: 4<br>
18211171; None<br>
56265 is Palindrome ; Attempt: 4<br>
1552551 is Palindrome ; Attempt: 3<br>
Exception in thread "main" java.lang.NumberFormatException: For input string: "2284457131"<br>
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)<br>
at java.lang.Integer.parseInt(Integer.java:583)<br>
at java.lang.Integer.parseInt(Integer.java:615)<br>
at palimdrone.reverse(palimdrone.java:61)<br>
at palimdrone.main(palimdrone.java:34)<br>
2284457131 is greater than Integer.MAX_VALUE. Try using Long.parseLong(reverse) instead of Integer.parseInt(reverse).
It's better to parse the input as String instead of number. So you will never have to worry about overflow.
static boolean isPalindrome(String str) {
StringBuilder strBuilder = new StringBuilder(str);
strBuilder = strBuilder.reverse();
return str.equals(strBuilder.toString());
}
take input as String or convert the integer to string
Scanner scan = new Scanner(System.in);
String input = scan.next();
System.out.println(isPalindrome(input));

find all palindromes in string

I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}

Categories

Resources