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

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));

Related

Java changing upper or lower case by entering CAPS

i want to write a program which at first it gets an integer number which is the number of strings of characters that are supposed to be entered including CAPS and i want that after each CAPS that was entered the rest of characters change in upper or lower case (the default is lower case at first) and finally the program outputs the final string. here is an example:
input:
8
s
f
k
CAPS
h
j
CAPS
p
output:
sfkHJp
here is what i tried so far first i wanted to check out whether this algorithm will work out or not but it actually did not because it does not print the result at all !
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int CAPScounter = 0;
String result = "";
String temp = "";
String singles = "";
boolean CAPSval = false;
if (CAPSval) {
singles = "CAPS";
}
Scanner input = new Scanner(System.in);
int n = input.nextInt();
// System.out.print(n);
while (true) {
if (result.length() == n - CAPScounter) {
break;
}
//temp += input.next();
singles = input.next();
if (CAPSval) {
CAPScounter += 1;
result += temp;
temp = "";
}
}
System.out.print(result);
}
}
This could be a simple solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String result = "";
String singles = "";
boolean isCAPSEnabled = false;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
singles = input.next();
if (singles.equals("CAPS")) {
isCAPSEnabled = !isCAPSEnabled; // reverse
} else {
result += isCAPSEnabled ? singles.toUpperCase() : singles.toLowerCase();
}
}
System.out.print(result);
}
}
you can set limit for while
CAPSval if first button second it value equal false or true
if CAPSval == true single change to Upper else toLower
if n == 0 while end and output result
Sorry I update solution you nofify first time button caps and If not button caps you enter upper or lower character then output same with enter
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int CAPScounter = 0;
String result = "";
String singles = "";
boolean CAPSval = false, fistButton = false;
Scanner input = new Scanner(System.in);
int n = input.nextInt();
while (n-- > 0) {
singles = input.next();
if (singles.equals("CAPS")) {
fistButton = true;
CAPSval = !CAPSval;
CAPScounter += 1;
} else {
if (fistButton) {
if (CAPSval)
singles = singles.toUpperCase();
else singles = singles.toLowerCase();
}
result += singles;
}
}
System.out.print(result);
}
}

how to replace an integer array with characters in 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());
}

JAVA Reversing a string on multiple lines output

Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...
Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.
You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();

Java - string split error

I'm trying to split a string and return each sub-string to an array in Java (easier in c#) but the compiler is not having it. I keep getting an index out of bounds error when I try to call the value of any string in the array indexed higher than 0. Here's the code I'm using:
public class hello {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int setter = 3000;
String num = in.next();
String[] numbers = num.split(" ");
int j = numbers.length;
for (int i =0; i < numbers.length ; i++) {
System.out.println(numbers[i]);
}
System.out.println(j);
Even the length of the array being returned is 1.
As David Wallace said in comments: you should use nextLine from Scanner...
But... why read line to split into int?
public static void main(final String[] args) {
final Scanner in = new Scanner(System.in);
String line = null;
List<List<Integer>> all = new ArrayList<>();
while ((line = in.nextLine()) != null) {
final String[] tokens = line.split(" ");
List<Integer> forOneLine = new ArrayList<>();
for (final String token : tokens) {
try {
final Integer value = Integer.valueOf(token);
forOneLine.add(value);
} catch (final NumberFormatException e) {
// Not an Integer
}
}
all.add(forOneLine);
}
Is it ok now?
Ended up parsing to an integer
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String n = in.nextLine();
int ne = Integer.parseInt(n);
String m = in.nextLine();
String[] numbers = m.split(" ");
System.out.println(n);
System.out.println(m);
for (String string : numbers) {
System.out.println(string);
}
}

java beginner programming, putting strings in char array to filter input

in this code I've been trying to filter the characters in the array with a for-loop to a second array, but am unable to. Could anyone tell me what is exactly wrong with my code?
public class Deel1 {
public static void main(String[] args) {
String zinInvoer = getInput();
String zinUitvoer = filterZin(zinInvoer);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zinInvoer = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zinInvoer = scan.nextLine().trim();
}
if (zinInvoer.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zinInvoer;
}
static String filterZin(String zinInvoer) {
String zinUitvoer = "";
char ongefilterd[] = zinInvoer.toCharArray();
String nogFilteren = new String(ongefilterd);
char a = nogFilteren.charAt(97);
for (a = 97; a <= 122; a++) {
a = a += 32;
char gefilterd[] = //second array to be printed
}
System.out.println("Gefilterd: " + zinUitvoer);
return zinInvoer;
}
}
Sorry if it annoys you but I had to translate your variables into english in order to figure out what their purposes were.
First of all, it will always throw an exception when the string is less than 98 letters long because it looks for the 97th letter.
Second, the for loop in "filterZin" will only filter letter # 98, which I am guessing was not your intention.
Also, geFilterd should probably be created outside of the for loop, and in the for loop you (i guess) would want to do
geFilterd[a]=a+32;
a+=32;
Because I couldn't figure out what your overall goal was for this program, I made a version of it that does what I think you were trying to do, but again, I do not know.
import java.util.Scanner;
public class Deel1 {
public static void main(String[] args) {
String phraseInput = getInput();
filterPhrase(phraseInput);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String phraseInput = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
phraseInput = scan.nextLine().trim();
}
if (phraseInput.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return phraseInput;
}
static String filterPhrase(String phraseInput) {
String phraseOutput = "";
char onFiltered[] = phraseInput.toCharArray();
String currentFilter = new String(onFiltered);
// for (a = 97; a <= 122; a++) {
// a = a += 32;
// //char filtered[] = //second array to be printed
// }
char[] filtered = new char[26];
for(int i=97;i<=122;i++){
char a = currentFilter.charAt(i);
filtered[i-97]= (char) (a+32);
}
System.out.println("filtered: " + filtered.toString());
return phraseInput;
}
}

Categories

Resources