+ 1
[SOLVED] Can someone show me how char works
I'm trying to do the lessons 7.1 on Java called Computer Speak, where a user inputs a letter and I have to print it out as a number, but I don't understand how char works so my code won't work import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String[] char a =read.next().charAt(0); int count=97; for(int i=0;i!=25;i++) { if(char a[i]==a) { char.replace[i]==count; } System.out.println(char[i]); count++; } //your code goes here }
9 Answers
+ 3
char[] a will declare character array , not single character and you cant assign single character by that way..
Just do
char a = read.next().charAt(0);
and
if(a='a'||'A') will assign 'a' in a. And it returns always true.
if you are trying about checking a have 'a' or 'A' then it must be like
if( a== 'a' || a== 'A' )
Edit: Serana Zentha after removing error in your above updated code ,it just prints a space if 'if clouse is true' otherwise nothing..
+ 3
Character declaration is just like :
ex: char a='a';
so you just need
char ch=read.next().charAt(0);
This will read a word but take only a charecter at index 0. and assign it into charecter variable ch.
You have wrong syntax in if condition.
To print it as a number, print its ascii value by casting it to int type as System.out.println( (int)ch);
+ 2
Post your updated code..
String[] char a =read.next().charAt(0);
if(char a[i]==a)
char.replace[i]==count;
These 3 lines have wrong syntaxes.. Not valid statements.
If you checking 'a' then it must be
if(a == 'a')
About 3rd => i dont understand what you tried there..
+ 1
Jayakrishna🇮🇳 i keep getting no output, no matter how I try to print it or cast it. it won't let me cast it
+ 1
Jayakrishna🇮🇳 im trying to print a letter as a number by casting but i have no idea what this lesson even wants me to do as it throws char in my fave despite the fact I have no idea what char even does
+ 1
Jayakrishna🇮🇳 I tried doing something simple just to print char a but this wint print either, I have no idea what I'm doing
i dont know how my syntax is wrong because i don't use char to begin with, could you please explain why my syntax is wrong, I know it's wrong but I don't know why I don't use char at all
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
char[] a = read.next().charAt(0);
for(int i=0;i!=25;i++)
{
if(a='a'||'A')
{
System.out.println(" ");
}
}
+ 1
Jayakrishna🇮🇳 thank you ill let you know if it works
+ 1
Jayakrishna🇮🇳 it worked thank you soooo much i was starting to lose my mind
+ 1
//sample code for casting.., check this once if you need..
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char ch=in.next().charAt(0);
System.out.print((int)ch);
}
}
//Edit: Serana Zentha you're welcome..