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();
Related
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.
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);
I wrote a program which prints out the characters of the sentence (or word) wrote by the user to the console. I thought that the program will end after I gave the first input. But it didn't and kept taking inputs and printing it even after it printed the first sentence. Can you explain me why it happened so? I am new to this. Here is the program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
/*
* This program prints out the characters written in the console
* line by line.
*/
public class ReaderProgram {
public static void main(String args[]) throws IOException{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do{
//reads character and stores it in c
c = (char) br.read();
//prints out c
System.out.println(c);
}while(c != -1);
//'while' checks if c is -1 (-1 means end of the stream)
}
}
Output is shown here (Input to console is show like this):
Epic
E
p
i
c
Dream
D
r
e
a
m
You have cast the result of br.read() too early.
br.read() returns a int, which has a larger storage capacity than a char. char is neither signed nor large enough to store both -1 and the full UTF-16 range of values.
By casting the result to a char before comparing it to -1 you have effectively converted -1 to Character.MAX_VALUE. Which can never equal -1.
Consider the following code:
public static void main( String[] args ) {
char v = (char) -1;
System.out.println( "v = " + (int) v );
}
It will print 65535, and not -1.
I'm trying to sort a list of strings in array into alphabetical order without using the sort method.
public static String[] sortedAdjectives(String[] original)
{
String[] sortedArray;
int aValue = 65;
String word = "";
sortedArray = new String[25];
for(int i = 0; i <25; i++)
{
original[i]=word;
char c = word.charAt(0);
sortedArray[c-aValue]=word;
}
return sortedArray;
Is my method, and
public static void main(String[] args) throws FileNotFoundException {
Scanner names = new Scanner(new File("names.txt"));
Scanner adjectives = new Scanner(new File("adjectives.txt"));
String[] adjectiveArray;
adjectiveArray = new String[25];
int counter = 0;
while (counter<25)
{
String in = adjectives.next();
fixCapitalization(in); //method that fixes capitalization
adjectiveArray[counter]=in;
counter++;
}
sortedAdjectives(adjectiveArray);
Is where I put the items from the file into an array. I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hmwk.sortedAdjectives(Hmwk.java:56)
at Hmwk.main(Hmwk.java:24)
When I try to run my program and I can't figure out where I'm going wrong. If you could point me in the right direction i'd be much appreciative. Thanks for your time.
You have word initialized as an empty string:
String word = "";
Then you are calling charAt(0) on an empty string. Can't do that.
Your string needs to be at least longer than 1 character in order to call that method.
You made a little mistake in the for loop.
It should probably be word = original[i]; which you did it inversely and makes the word never take the original parameter as reference.
Also a few things to improve here: using arraylist would have better extensibility and avoid erasing repetitive letters.
I have a text file having names separated by tab. I need to print the name at the given input number. like i have
abc def ghi jkl mno
when the user enters 2, it should print "def". What i did is
import java.io.*;
import java.util.*;
public class NamesTab {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char ch;
System.out.println("Enter the Number: ");
ch=(char) br.read();
System.out.println(ch);
BufferedReader s = new BufferedReader(new FileReader("Ass1.txt"));
String c=s.readLine();
String[] tokens = c.split("\t");
System.out.println(tokens[1]);
}}
but i could not pass the "ch" to "tokens[ch]". please help me.
You can use ch-'0' for single-digit numbers.
System.out.println(tokens[ch-'0']);
You're attempting to provide a character in a space which should be an Integer. I understand that this "should" work in java, but just to be safe, cast ch to an int when you're getting the index of the String array containing the characters you want.
System.out.println(tokens[(int)ch]);
Can we assume that ch always refers to a number between 0 to 9? If so, ch - '0' should do the trick.