I am trying to convert character values to ASCII values in java.
Below is my code.
public class test {
public static void main(String[] args)
{
System.out.println("Enter the string to be converted");
Scanner input = new Scanner(System.in);
String str =input.nextLine();
char ch[]=str.toCharArray();//hello
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
input.close();
}
}
I want to get the string from the user, and store it in an array(which I a m doing it in ch[]) and for each element in array, I want to print its corresponding ASCII value.
But at line char ascii[i]=ch[i]; the interpreter is telling Type mismatch: cannot convert from char to char[].
Where is the problem ? as both of my character initialization are arrays, then why is it telling that its type mismatch ?
Note: I want the ascii variable to be stored as an array only.
You can't assign a char to a char array.
Change
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
to
for(int i =0;i<str.length();i++)
{
char ascii = ch[i];
System.out.println((int)ascii);
}
EDIT:
If you wish to store the output in an array, you should declare the array before the loop :
char[] ascii = new char[str.length()];
for(int i =0;i<str.length();i++)
{
ascii[i] = ch[i];
System.out.println((int)ascii[i]);
}
when you declare ascii[i], you are trying to initialize a character array, but you are assigning it ch[i], which is a single character. Hence you get the error:
Type mismatch: cannot convert from char to char[].
As Eran said above, changing ascii variable from char array to character will resolve the issue.
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.
import java.util.*;
public class prac9
{
public static void main(String[] args){
Scanner scn=new Scanner(System.in);
int count=0;
String x,str=" ";
System.out.println("Regular Expression is (a+b)(ab+ba)*");
System.out.println("Enter a Word: ");
x=scn.nextLine(); //here simple x string type of varible
if(x[0]=="a"|| x[0]=="b") //here x array of string type of varible
{ //prac9.java:15: error: array
// required,but String found
for(int i=1; i<x.length(); i++)
{
str+=x[i];
if((i%2==0)==true)
{
if(str=="ab" || str=="ba")
{
count=count+2;
str=" ";
}
}
}
if((count+1)==(x.length())){
System.out.println("Acceptable");
}
else{
System.out.println("Not Acceptable");
}
}
else{
System.out.println("Not Acceptable..");
}
}
Please help me as simply as possible. It gives me an error as I mentioned in above comment. I know what it is saying, but I can't figure out how to convert a String into an array so I can check every single character given by a user.
Actually, this code was written in C++. I just converted it into Java language.
if(x[0]=="a"|| x[0]=="b")
can be changed to:
if(x.startsWith("a") || x.startsWith("b"))
and
str+=x[i];
can be changed to:
str+=x.charAt(i);
and lastly:
if(str=="ab" || str=="ba")
should be changed to
if(str.equals("ab") || str.equals("ba"))
You can access the first character of the string using charAt as follows -
x.charAt(0) == 'a'
since that would return the first character of the string (based of start index = 0)
x is a String, you'd need to convert it to an array of chars, then compare each char with 'a' and 'b'. To do that replace this line of code if(x[0]=="a"|| x[0]=="b") by
char[] x_chars = x.toCharArray();
if (x_chars[0] == 'a' || x_chars[0] == 'b') {
...
}
If one checks the documentation
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
you can find the method
x.charAt(0)
which is used in java instead of x[0].
Your "x" variable is of String type, not an array. To declare "x" as string array, you should use
String x[] = new String[n]; //here 'n' is number of elements you store in your 'x' array
Also if you don't know how many elements can be are to be included in array, that can also grow and shrink based on your requirement you can use "ArrayList " like this;
ArrayList<String> al=new ArrayList<String>();
al.add("J"); //add 'J' as 1st element of 'al'
al.add("a");
al.add("v");
al.add("a");
System.out.println("element at 2nd position: "+al.get(2)); //get 'a'
al.remove(0) //to remove 'J'
.............
I am trying to make a 2D array that stores character values and I keep running into errors. Here's the code I have so far.
public static void main(String[] args) {
char[][] text;
text = new char[20][45];
// Enter your message into the array
char text[][] = {{A, ,b,i,g, },{d,o,g, ,a,t,e},{ ,a, ,p,i,g}};
java.util.Scanner input = new Scanner(System.in);
for (char column = 0; column < text[0].length; column++) {
for (char row = 0; row < text.length; row++) {
System.out.println(text[row][column] + " " );
}
System.out.println();
}
}
}
I am also trying to print the values in column major order. How do I make this 2D array store letters? When I put letters into the array I get an error saying "A cannot be resolved to a variable, b cannot be resolved to a variable, etc." How do I set the array up so it can store these values and not result in errors?
A quick answer with thanks to #Kon in the comments:
Characters need to have quotes around them. If I execute
char[][] text;
text = new char[20][45];
char text[][] = {{h, i},{ ,b , o ,b}};
Firstly, I would already get the error Duplicate local variable text because you are defining text 2 times: One when you say char[][] text; and the other time when you say char text[][] =. Assuming you fixed that and put the right code, you still have a problem:
YOU DON'T HAVE THE CHARACTERS RIGHT Next time, do this
{{'h', 'i'}, {' ', 'b', 'o', 'b'}}
Instead of
{{h, i}, { , b, o, b}}
I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value
I'm having problems with inputting data interactively into arrays. I'm trying to use the nextLine method to add a set of 12 names into the array, but when I compile at the end of line 12 it gives me the error "Incompatible Types".
public class nextLineArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char names[] = new char[12];
System.out.println("Enter the 12 names: ");
for(int i = 0; i < 12; i++) {
names[i] = input.nextLine();
}
System.out.println(names);
}
}
This is because the Scanner.nextLine() returns a String, not a char
Try changing
char names[]=new char[12];
To
String names[] = new String[12];
Why do you use Char for storing names?? Use Strings instead.
And also nextLine() returns a String not a char. So the error.
Just FYI... you can even use next() to get the input from console if you doesnt want the input to be null or empty. nextLine() takes even an empty string as input. Try next()