Why to add a Empty String while adding an string with int? - java

In the below when I wasn't adding the ""(Empty String), the output was in int, which is pretty abnormal because adding a String with an int always gives a string. But as soon as I added the Empty String thing, the code seemed to work fine. In both the cases,I was adding a string from the string array that I created earlier in the code.
import java.io.*;
public class TooLong{
public static void main(String[] args) throws IOException{
InputStreamReader n = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(n);
byte i ;
i=Byte.parseByte(input.readLine());
String origWords[] = new String[i];
for (int j=0;j<i;j++) origWords[j]= input.readLine();
for (int j=0;j<i;j++){
int charLength = origWords[j].length();
if (charLength < 11) System.out.println(origWords[j]);
else System.out.println(origWords[j].charAt(0) +""+ (charLength-2) + origWords[j].charAt(charLength-1) );
}
}
}

I assume, you are trying to achieve “internationalization ⇒ i18n”
That is because String.charAt(int) returns char. Which will be treated as numerical when using +.
By using + with the empty String you force the compiler to convert everything to String
You can use String.substring(0,1) instead of the first charAt to force type String conversion

The charAt() method of String returns the char. char is one of the primitive data types. char is a textual primitive, however, it also can do arithmetic operations like numerical primitives. The codes below are examples for it:
`public static void main(String args[]){
String st = "i am a string";
char c = st.charAt(0);
System.out.println(c);
System.out.println(c+ st.charAt(2));
System.out.println(c+ "" + st.charAt(2));
}
`
The result of the above code will be:
i
202
ia
Hope this example makes it clear.

Related

Making a loop that returns the characters before it hits a colon character

Whenever I run my code it returns this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at codes.Main.main(Main.java:10)
Here is my code:
package codes;
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
String cord2 = "Name: x=200 y=20 z= 300";
int c1 = cord1.length();
String mychar = String.valueOf("cord1".charAt(0));
for (int a = 0; a < c1; a++){
mychar = String.valueOf("cord1".charAt(a));
if (mychar == ":"){
break;
}else{
cord1.substring(a);
}
}
}
}
There are multiple things wrong in your code..
mychar == ":" should be mychar.equals(":") instead. Since Strings are immutable, we need to use the .equals to compare them instead of == (<- this checks if the references are equal instead of the String-values).
"cord1".charAt should be your variable cord1.charAt.. By using "cord1" you basically create a new String with the value cord1.
cord1.substring(a); doesn't change the cord1 value, but returns a new String. So you'll have to save this String result, or print it, and then stop the loop with a break.
Using cord1 = cord1.substring(a) would shorten the String itself. Since you still loop in the range [0, c1) where c1 was the original String, we would still get a StringIndexOutOfBoundsException. Instead, you don't need the else-case and need both the cord1 = cord1.substring(a) and break inside the if-case. (Also, I assume you want to remove the : itself as well, so you'll have to use .substring(a+1) instead.)
Also, why use String.valueOf( char ) instead of just using the char themselves? Not really a requirement, but the String.valueOf is kinda redundant here, and makes the code less readable.
Putting it all together:
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
System.out.println("cord1 before:\t" + cord1);
int c1 = cord1.length();
char mychar = cord1.charAt(0);
for (int a = 0; a < c1; a++){
mychar = cord1.charAt(a);
if (mychar == ':'){
cord1 = cord1.substring(a+1);
break;
}
}
System.out.println("cord1 after:\t" + cord1);
}
}
Which will result in cord1 having the value " x=23 y=60 z= 600" (note the leading space) in the end.
Try it online.
Here is a much simpler alternative with the same result:
String cord1 = "Name: x=23 y=60 z= 600";
String cord1ExcludingName = cord1.replaceFirst("^.*:","");
Try it online.
^ : Only look at the start of the String for:
.* : Zero or more of any character,
: : followed by a `:`
Which will be replaced with "" (an empty String), so they're basically removed.
Use equals instead of "=="
Like this
if (mychar.equals(":")){
break;
You need to use equals method because you are working with a string. Whenever you work with string u must compare them with the method equals.
If you used
char myChar = .....
Your code would work. You can compare chars with "=="
String.valueOf("cord1".charAt(0)) means you are looking into the 0th character of string "cord1" which has a highest index of 4, that is why it is giving out of bound exception at 5.
What you have to do is String.valueof(cord1.charAt(0)). This will consider the string in the variable cord1.

locate specific char and replace it in Java

I am getting around a hundred url strings from my JSON. Example:
media.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_189765_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_162_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_532535677_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_1612452_**b.jpg**
media.life.com/homes/1000000/10000/6500/6404/6404_10976562**_b.jpg**
As you see, the only common thing in these urls is the end "b.jpg"
How can I replace the character b with other character?
I have tried with this method:
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
Here is when I call it:
hs.thumbNailUrl = changeCharInPosition(65, 'l',hs.thumbNailUrl);
But the position of b always changes, so this method is inefficient.
If you are always only going to have one char of that value you can just use .replace() to replace that character.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace('b', 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
Now if you are trying to replace based off of the index of the character you could use StringBuilder and find the location of b by using substring and finding the location of b by subtracting the the number of chars after b from the total length.
public static void main(String args[]) {
StringBuilder x = new StringBuilder("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x.setCharAt(x.length() - 7, 'y');
}
Output
amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**y.jpg**
EDIT
Third option:
Here we are replacing the char at the last index of 'b'.
public static void main(String args[]) {
String x = new String("amedia.life.com/homes/1000000/10000/6500/6404/6404_1625646_**b.jpg**");
x = x.replace(x.charAt(x.lastIndexOf('b')), 'y');
System.out.println(x);
}
Now obviously you can loop through and use a new character for each string.
Change your call to changeCharInPosition from
hs.thumbNailUrl = changeCharInPosition(65, 'l', hs.thumbNailUrl);
to
hs.thumbNailUrl = changeCharInPosition(hs.thumbNailUrl.indexOf("b.jpg"),
'l', hs.thumbNailUrl);
You can use String.lastIndexOf(String) in order to find the last occurrence of one String inside another.
e.g.
private String replace(String url, String thumnailUri){
String toReplace = "**b.jpg**";
int lastBIndex = url.lastIndexOf(toReplace);
return url.substring(0, lastBIndex) + thumnailUri;
}
You could also use String.replace(String, String) e.g.
url.replace("**b.jpg**", hs.thumnailUri);

Basic Java program giving wrong ouput

I'm getting just spaces after running this code, it is not even printing "ABC"..
import java.io.*;
class Str{
public static void main( String args[])
{
String a = "abc";
char ch[] = new char[2];
a.getChars(0,0,ch,1);
PrintWriter pw = new PrintWriter(System.out);
pw.println(ch);
pw.println("ABC");
pw.println(ch);
System.out.println(ch);
}
}
getChars uses parameters (int srcBegin, int srcEnd, char[] dest, int destBegin). Your srcBegin and srcEnd are both 0.
srcBegin needs to be 0 in your case, but srcEnd needs to be 3.
This works:
a.getChars(0,3,ch,0);
And you need a char array with the length 3 and not 2, so change char ch[]=new char[2] to char ch[]=new char[3]
To copy only the first character into the ch array at index 1:
a.getChars(0,1,ch,1);
It seems you are lacking calling pw.flush(), then something shows up. That should be the result of your program. You might have to change parameters in String.getChars() method according to this Java tutorial, as you are receiving an empty array.
String a="abc";
char ch[]=new char[2];
a.getChars(1,2,ch,1); //Put indexes to first 2 positions to mark srcBegin, srcEnd
PrintWriter pw=new PrintWriter(System.out);
pw.println(ch);
pw.println("ABC");
pw.println(ch);
pw.flush();

How does one add extremely large values in Java?

I've tried the code below, but I'm getting an error. How would I go about adding two large values represented as strings together?
public class LargeAddition {
static String testcase1 = "987659876598765";
static String testcase2 = "9999999999999999999999999988888888888";//can we add this kind of large num
public static void main(String args[]){
LargeAddition testInstance = new LargeAddition();
String result = testInstance.add(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public String add(String str1, String str2){
Long num=000000000000000L;
//String str="";
num=Long.parseLong(str1)+Long.parseLong(str2);
//String str=num.toString();
return num.toString();
}
}
Use BigInteger, Long is short for these values.
public static String add(String str1, String str2) {
BigInteger big1 = new BigInteger(str1);
BigInteger big2 = new BigInteger(str2);
final BigInteger num = big1.add(big2);
return num.toString();
}
Since this is an a homework assignment and you don't/can't use classes such as BigInteger, I'll go through a more tedious and manual way to do it (although a good introduction assignment).
You can loop through the two String-integers from size-1 to 0.
String integer1 = "1230"
String integer2 = "9999999"
for(int i = integer1.size; i >= 0; i--){
//addition
}
However, this is may be an issue since the two String-integers have different sizes. I would create a method that will add additional zeroes to the front of the smaller String-integer so both String-integers match in size. Ex. "1230" -> "0001230"
Before looping, create an output String-inter which equals to an empty-String.
String outputInt = "";
Convert each char to an int, then do the addition.
int tempResult = Integer.parseInteger(integer1.indexOf(i)) + Integer.parseInteger(integer2.indexOf(i))
If you get a single digit, convert it to a String and append to output String-integer. If you get a double digit, then only put append the second digit and carry over the first digit to the next calculation.
String tempResultStr = //convert tempResult into a String
if(tempResultStr .size == 1){
//handle single digit case
}else{
//handle double digit case
//use a variable to declare carry over
}
Remember to handle the case if you have to carry over and there is nothing to carry over to.
NOTE: This is pseudo code for most part
If you run
System.out.println(Long.MAX_VALUE);
you'll get
9223372036854775807
your values are far greater
9999999999999999999999999988888888888
so the way is to use BigDecimal
BigDecimal bd = new BigDecimal("9999999999999999999999999988888888888");
System.out.println(bd.multiply(bd));
gives you
99999999999999999999999999777777777760000000000000000123456790143209876544

Arrays.toString() prints String with [] and , ---any alternative?

while programming i accepted a string ...changed it to char array using
string.toCharArray()
...and had to change it back to string (because i am using recurion and have to pass the string as argument each time)..how to do this..???
i tried using array.toString()...but it passes gibberis..beginning with #....then i searched here and found out about Arrays.toString().....but learned that it does indeed convert it to string but adds [] and , ...i need the original string....how to go about this...heres part of the code..
public String replace(String str, char ch) {
if(count ==0){
Scanner sc2= new Scanner(System.in);
System.out.println("enter the character to be replaced with ");
c2 =sc2.next().charAt(0);
len=str.length();
}
arr=str.toCharArray();
if(arr[count]==ch){
arr[count]=c2;
}
count++;
str=Arrays.toString(arr); // Problem
if(count<len)
temp=replace(str,ch);
else
temp=str;
return temp;
}
Try this
String chString = new String(myCharArray);
If you want to convert a char[] to a String, then just use new String(array).
You can pass this array to String constructor:
String original = new String(arr);

Categories

Resources