Converting int to char
Hi!..
I have a problem!...
I need to convert integers to chars, but i`m using char(int)....
So, only accept until ascii code 128..
Please, What can I do?
This is my code:
Thanks!
public Convert() {
public static void main(String[] args) {
Convert convert1 = new Convert();
System.out.print(f_Transforma("ABCD"));
public static String f_Transforma(String Password)
int IntStrLong=Password.length();
String StrResultado=new String();
while (IntStrLong >=1)
int tmpchar=(int)Password.charAt(IntStrLong-1); //valor ascii
tmpchar=256-tmpchar+IntStrLong;
String aChar = new Character((char)tmpchar).toString(); //ASCII code to String
StrResultado=StrResultado+aChar;
IntStrLong-=1;
return (StrResultado);
}
I did what you told me and nothing happened...
int tmpchar=(int)Password.charAt(IntStrLong-1); //valor ascii
tmpchar=256-tmpchar+IntStrLong;
tmpchar=tmpchar>>8;
String aChar = new Character((char)tmpchar).toString(); //ASCII code to String
Similar Messages
-
HOW can I convert int value char TO String
I am trying to study Java by books, but sometimes it is quite difficult to find answers even to simple questions...
I am writing a program that analyzes a Chinese text in Unicode. What I get from the text is CHAR int value (in decimals), and now I need to find them in another text file (with RegEx). But I can't find a way how to convert an INT value of a char into a String.
Could you help me?
Thank you in advance.You are confusing matters a bit. A char is a char is a char, no matter
how you represent it. Have a look at this:char a= 'A';
char b= 65;Both a and b have the same value. The representation of that value
can be 'A' or 65 or even (char)('B'-1), because the decimal representation
of 'B' is 66. Note the funny construct (char)(...). This construct casts
the value ... back to the char type. Java performs all non-fraction
arithmetic using four byte integers. The cast transforms it back to
a two byte char type.
Strings are just concatenations of zero or more chars. the charAt(i)
method returns you the i-th char in a string. Have a look:String s= "AB";
char a= 'A';
char b= (char)(a+1);
if (a == s.charAt(0)) System.out.println("yep");
if (b == s.charAt(1)) System.out.println("yep");This piece of code prints "yep" two times. If you want to compare two
Strings instead, you have to do this:String s= "AB";
char a= 'A';
char b= 'B';
String t= ""+a+b;
if (s.equals(t)) System.out.println("yep");Note the 'equals' method instead of the '==' operator. Also note that
string t was constructed using those two chars. The above was a
shorthand of something like this:StringBuffer sb= new StringBuffer("");
sb.append(a);
sb.append(b);
String t= sb.toString();This is all handled by the compiler, for now, you can simply use the '+'
operator if you want to append a char to a string. Note that it is not
very efficient, but it'll do for now.
Does this get your started?
kind regards,
Jos -
Necesito convertir un entro a un caracter por ejemplo si en el panel frontal tengo una perilla y la posiciono en el 0, necesito obtener una A, si la posiciono en 1, necesito obtener una B y asi sucecivamente, voy a adjuntar lo que llevo echo hasta el momento. Lo estoy haciendo con la herramienta format to string pero no se bien como usarla, no se si pueda hacer de otra manera
De antemano gracias por la ayuda
Attachments:
control motores.vi 35 KBHi edcames,
with this code you can transform your numbers to chars.
Hope it helps.
Mike
Message Edited by MikeS81 on 07-16-2008 08:56 AM
Attachments:
Unbenannt1.PNG 3 KB -
Hi,
How can I convert from an int to char?The challange is to convert from int to String without using any API or automatic conversionWoah, what a challenge ! Why ?
Anyway, what about a recursive call and switch statement. Something likepublic String intToString(int n) {
if(n<0) {
return "-"+intToString(-n);
if(n<10) {
return getStringDigit(n);
else {
return intToString(n/10) + getStringDigit(n%10);
private String getStringDigit(int n) {
switch(n) {
case 0:
return "0";
// etc.
} -
Necesito saber cual es la instruccion en cvi que convierte int a char
Usa sprintf(char Destino, const char Formato, origen_de_datos), que esta en la libreria ANSI C. Es una funcion general que genera un string de chars con cualquier tipo de datos.
Debes declarar un char Destino del largo necesario para que contenga todo el numero (aprox. 6 caracteres para un int). El char formato es del tipo "%d" para un entero
Ej
int Entero;
char EnteroConvertido[6];
sprintf(EnteroConvertido,"%d",Entero); -
Int to Char...I don't know what the problem is here
Everything compiles fine here, and if I print out the "encryption" variable I get what looks like it would be right, converted into chars, but when I try to convert the int to char(my char variable for that is 'w'), my compiler freaks out, I don't even know what it's doing it doesn't give me an error, but sometimes it prints out nothing but sometimes it prints out "puTTypUTtypuTTYPUtty" ...why is it doing that and what is wrong with what I am doing?.
public class encrypt
public static void main(String[] args)
String plainText = "hello, my name is christy.";
String keyWord = "nice to meet you";
int encryption = 0;
char ch = 'a';
char c = 'a';
int encryptor = 0;
int charCode;
int sum = 0;
char w;
int i = plainText.length();
int j = plainText.length();
int[] plain = new int;
int[] key = new int[j];
for(i=0; i<plainText.length(); i++)
ch = plainText.charAt(i);
charCode = (int)ch;
if(charCode > 97 && charCode < 122)//make lowercase
{charCode = charCode - 97;}
if(charCode > 65 && charCode < 90)
{charCode = charCode - 65;}
plain[i] = charCode;
for(j=0; j<keyWord.length(); j++)
c = keyWord.charAt(j);
int chCode = (int)c;
if(chCode > 97 && chCode < 122)
{chCode = chCode - 97;}
if(chCode > 65 && chCode < 90)
{chCode = chCode - 65;}
key[j] = chCode;
encryption = (plain[i] + key[j]) % 26;
w = (char)encryption;
System.out.print(w);And for that matter, use increment/decrement assignment operators (like += and -=) instead of verbosely repeating the variable. And if you're going to use character-by-character case conversion, use the methods in Character don't do it like a C programmer circa 1982. And if this is anything other than a homework assignment, use encryption code provided in the JDK; don't reinvent it.
-
Req. help on converting int value to a character(ASCII?)
I have an array, letter[x]...where x is an int from 0 to 26. Each element is storing the freq of a particular letter in a piece of text.
how do I convert back so that I can store the most freq letter in a string...I presume it's by using the ascii code but I don't know how.
here's the problem code...
if (letter[x]>currentMostCommon)
mostCommonLetter=x; // Don't want value of x, I want ascii for letter "a" ie. x+97
}Yes, it was meant to be 0-25...silly error.
Thanks for the advice, however your suggestion gives an error:
C:\MYDOCU~1\SUBJECTS\COMPPR~1\MYPROG~1\ASSIGN2\AnalyseText.java:61: possible loss of precision
found : int
required: char
char c= 'a' + x;
any suggestions?
Paul -
CAST Not working for me - Arithmetic overflow error converting int to data type numeric - error
GPM is DECIMAL(5,2)
PRICE is DECIMAL(11,4)
COST is DECIMAL(7,2)
Trying to update the Gross Profit Margin % field and I keep getting the "Arithmetic overflow error converting int to data type numeric" error.
UPDATE SMEMODETAIL SET SMD_GPM = (SMD_PRICE-SMD_COST) / SMD_PRICE * 100
FROM SMEMODETAIL WHERE SMD_PRICE<>0 AND SMD_QUANTITY<>0
Example record:
SMD_PRICE SMD_COST GPM%
1.8500 1.62 12.4324324324324300
I added cast and I still get the error.
How do I format to get this to work?
Thanks!Hi GBerthume,
The error is caused by some value such as 1000.01 of the expression (SMD_PRICE-SMD_COST) / SMD_PRICE * 100 exceeds the
precision of the column(DECIMAL(5,2)). The example data doesn't cause the overflow error for the value of the expression is 12.43 which is in the scope of DECIMAL(5,2).
USE TestDB
CREATE TABLE SMEMODETAIL
SMD_PRICE DECIMAL(11,4),
SMD_COST DECIMAL(7,2),
SMD_GPM DECIMAL(5,2)
INSERT INTO SMEMODETAIL(SMD_PRICE,SMD_COST) SELECT 1.8500,1.62
UPDATE SMEMODETAIL SET SMD_GPM = (SMD_PRICE-SMD_COST) / SMD_PRICE * 100
FROM SMEMODETAIL WHERE SMD_PRICE<>0-- AND SMD_QUANTITY<>0
SELECT * FROM SMEMODETAIL
DROP TABLE SMEMODETAIL
The solution of your case can be either scale the DECIMAL(5,2) or follow the suggestion in Scott_morris-ga's to check and fix your data.
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
I've got a method I'm working on that looks like this:
private static String generatePassword()
String pass = "";
int randomInt;
char a;
for(int i = 1; i <= PASSWORD_LENGTH; i++)
randomInt = generator.nextInt();
a = (char)randomInt;
pass = pass + a;
System.out.print(pass);
return pass;
What I'm trying to do here is create a randomly generated password that consists of five characters. Password_Length is a static variable set to 5. I'm having a problem typecasting the randomInt into a character. Everytime I do this, my display comes back as 'boxes' for each character. If anyone can help, it'd be appriciated.private static String generatePassword()
String pass = "";
int randomInt;
char a;
for(int i = 1; i <= PASSWORD_LENGTH; i++)
randomInt = (int)(((double)('z'-'a'))*java.lang.Math.random());
if(java.lang.Math.random()<0.5)
randomInt -= ('a'-'A');
a = (char)randomInt;
pass = pass + a;
System.out.print(pass);
return pass;
} -
Converting a 6 char string to date
Please help..
How can I convert a 6 char date (ddmmyy) to date format
that can be passed as input to function module?Hi,
Try FM,
CONVERT_DATE_TO_INTERNAL
Run this sample code,
DATA:
my_date(6) TYPE c VALUE '300708',
w_date TYPE sy-datum.
CALL FUNCTION 'CONVERT_DATE_TO_INTERNAL'
EXPORTING
date_external = my_date
* ACCEPT_INITIAL_DATE = ACCEPT_INITIAL_DATE
IMPORTING
date_internal = w_date
EXCEPTIONS
date_external_is_invalid = 1.
WRITE: w_date.
Regards
Adil -
From int to char...
Got a nice little problem: I have an int (e.g. int i = 111). This should be transformed into the appropriate ASCII-Code char (or UNICODE-char, if only this is possible). Sounds easy but I didn't manage it.
In desperate need for help... :-)
Hannibal_
Thanx!Have you ever tried to cast an int to char? I've tried it for hours now but I didn't get it right. There is no problem to specify a char by giving it an int value (char c = 111) but to cast an int to char. It's not possible to do it like this:
char c;
int i = 111;
c = i;
Thanx! -
Can't convert int to int[] URGENT!
HI list!
Here is the code part I have:
/** Holds the permutated groups which are arrays of integers. */
Vector v;
if(arg.length<3) System.exit (0); //Need at least 3 arguments
elements=new int[arg.length-1]; //Create array to hold elements
/* Copy the arguments into the element array. */
for(i=0;i<arg.length-1;i++) elements=Integer.parseInt(arg[i+1]);
groupsize=Integer.parseInt(arg[0]); //Get the number in each group.
calc(groupsize,elements.length); //Find out how many permutations there are.
v=permutate(groupsize,elements); //Do the permutation
for(i=0;i<v.size();i++) { //Print out the result
elements=(int[]) v.get(i);
System.out.println("");
for(j=0;j<elements.length;j++) System.out.print(elements
[j]+" ");
System.out.println("\nTotal permutations = "+v.size());
and the error I get is:
Permutate.java:26: Incompatible type for =. Can't convert int to int[]. for(i=0;i<arg.length-1;i++) elements=Integer.parseInt(arg[i+1]);elements=(int[]) v.get(i);
The above statement is illegal. Its not possible to
use an array type in casting at all.
Basically you are trying to do a kind of multiple
casting, which is not possible.
You might want to store vectors in vector v instead of
arrays in vector v. Its better to do this.There's nothing wrong with the line
elements = (int[]) v.get(i);
assuming the returned object from the vector is in fact an array of int. Even then, it is a runtime exception condition not a compile-time error.
Using arrays is perfectly valid where you know the size of the array at creation and do not need to resize it during use... The arrays are fast and compact. This is however not a comment on the approach taken in this case but merely an observation that arrays are not always an inferior choice to one of the collection classes.
Now put up your dukes... ;) -
Can't convert int to java.lang.Integer.
Hi everyone.
I'm working on an auction site at the moment and have problems gaining a bidID number. This is part of my code and my error.
AuctionFacade aHse = (AuctionFacade) application.getAttribute("AuctionFacade");
String strTraderName = (String)session.getAttribute("traderName");
String strPassword = (String)session.getAttribute("password");
String strIDNum = request.getParameter("auctionID");
Integer intID = Integer.valueOf(strIDNum);
Integer [] bids = aHse.getAllBids(intID);
float fltYourBid = aHse.getBidPrice(bids.length);
^
Can't convert int to java.lang.Integer.
can anyone help please?So, does "aHse.getBidPrice" expect an int or an Integer as its parameter? And does it return an int, or an Integer, or what? The answer to those questions may lead to your solution -- look at what you are actually using as the parameter, for example.
-
Can't convert int to java.lang.Object
When I deploy my customer Bean, the following error occures, I think the main problem is Can't convert int to java.lang.Object, does anyone facing the same problem with me?
<pre>C:\j2sdkee1.3\repository\home\gnrtrTMP\CustomerApp\CustomerBean_RemoteHomeImpl.j
ava:27: Incompatible type for declaration. Can't convert int to java.lang.Object
java.lang.Object primaryKey = ejb.ejbCreate(param0, param1, para
m2);
^
C:\j2sdkee1.3\repository\home\gnrtrTMP\CustomerApp\CustomerBean_RemoteHomeImpl.j
ava:57: Incompatible type for =. Can't convert int to java.lang.Object.
primaryKeys = ejb.ejbFindByPrimaryKey( param0);
^</pre>
I really need your help!!!you can only convert one object type to another. Integer is an object int isnt. You might want to convert int to Integer and then go ahead.
see if it works. -
FM to convert double byte chars
Hi All,
Is there anyone know what are the function module to convert double-byte chars? Thanks.Seems like Blue Sky is not clear
You want to convert what into what?
Whats the purpose of this requirement, kindly give more details.
Regards
Karthik D
Maybe you are looking for
-
Error about database conenction
hi everyone i ve a problem about connecting to ms sql server. i ve made two tables on MSsql server names are rezervation and sale. those tables ve same column names. column names are name(varchar50) surname(varchar50) airline(varchar50) flight_no(nva
-
How do I create a bootable system CD?
I want to create a CD that will boot my Powerbook using OS X 10.4.9. I also want to add disk utility and various other Apple and non-Apple utilities (such as OnyX and ClamXAv) to that bootable CD so I can diagnose and repair disk issues in the 10.4.9
-
Why are my photo stream photos not showing up in on my computer?
Only some of the pictures I take with my iPhone 4 are loading in iCloud and only some of those are showing up on my computer with iCloud operating. Please help.
-
JPEG decode: how to use it?
Hello experts, I am using Labview 7 Express and Windows XP. I am downloading continuous datastreams of JPEG images from network cameras (Motion-JPEG streams, not MPEG). I use the TCP Read VI to get the streams, and I save them to disk on the fly. It
-
Notifying a forms client from the database
I would like to notify a forms client of a certain things that happens in the database. I guess this could be done by having a timer polling a table at certain intervalls. I my case that solution is not good because I need a fast reaction (<2 sec) wh