I'm trying to my first program text to ASCII converter, but I have some problems, it's explained inside the code:
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii = ('convert'/1); // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
String x = "text"; // your scan text
for(int i =0; i< x.getLength(); x++){
System.out.println((int)x.charAt(i)); // A = 65, B = 66...etc...
}
(Maybe use Scanner.nextLine().)
import java.text.Normalizer;
import java.text.Normalizer.Form;
String ascii = Normalizer.normalize(myChars, Form.NFKD)
.replaceAll("\\P{ASCII}", "");
This splits all accented chars like ĉ into c and a zero length ^. And then all non-ascii (capital P = non-P) is removed.
Try this:
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
char[] charArray = myChars.toCharArray();
for (char character : charArray) {
System.out.println((int)character);
}
scanner.close();
}
This converts the string to a char array and then prints out the string representation of each character.
Replace this line
"int ascii = ('convert'/1);"
by
int ascii= (int)convert;
This should work.
This code will work
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii= (int)convert; // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
did you missed type casting the character to integer?
try this:
int ascii = (int) convert;
Related
I wrote a program that read input and then print it out.
public class inverse {
public static void main (String arg[]) throws IOException {
int input1 = System.in.read();
System.out.println(input1);
String temp= Integer.toString(input1);
System.out.println(temp);
int[] numtoarray =new int[temp.length()];
System.out.println(temp.length());
for (int i=0 ;i<temp.length(); i++)
{numtoarray[i]= temp.charAt(i);
System.out.println(numtoarray[i]+"*");
}
}}
but here when I write 123456 it print 49. but it should print 123456. what cause this problem?
123456 is an integer, but System.in.read() reads the next byte as input so it will not read the integer as expected. Use the Scanner#nextInt() method to read an integer:
Scanner input = new Scanner(System.in);
int input1 = input.nextInt();
Your numtoarray array will also print the bytes, not the individual characters of the integer parsed as a string. To print the characters, change the type to a char[]:
char[] numtoarray = new char[temp.length()];
System.out.println(temp.length());
for (int i = 0; i < temp.length(); i++) {
numtoarray[i] = temp.charAt(i);
System.out.println(numtoarray[i] + "*");
}
read() doesn't read a number, it reads one byte and returns its value as an int. If you enter a digit, you get back 48 + that digit because the digits 0 through 9 have the values 48 through 57 in the ASCII encoding.
You can use Scanner instead
Here is the code
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int input1 = in.nextInt();
System.out.println(input1);
String temp= Integer.toString(input1);
System.out.println(temp);
char[] numtoarray =new char[temp.length()];
System.out.println(temp.length());
for (int i=0 ;i<temp.length(); i++){
numtoarray[i]= temp.charAt(i);
System.out.println(numtoarray[i]+"*");
}
}
DEMO
I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}
I have new assignment and since I am new to JAVA I don't know how to make it work, I have searched this website frequently but all the solutions which were suggested didn't work out for me or I didn't use them properly, I would be grateful if someone helps me...
the code below is the most simple solution I could find but still doesn't work...
I want to get inputs like names from people and change them to numbers (int)...it says it is not possible to cast from string to int ... !!
package loveindex;
import java.util.Scanner;
//import java.math.BigInteger;
public class LoveIndex {
private static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
System.out.println(testi);
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
System.out.println(testi2);
int ascii = (int) testi;
int ascii = (int) testi2;
}
}
You Can Try This:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
System.out.println((int)ch+" ");
}
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch+" ");
}
scan.close();
}
Achieve the same in a concise way by employing Java 8's lambda function.
From your comment (at the accepted answer) you need the sum of the characters at the end?
String str = "name";
int sum = str.chars().reduce(0, Integer::sum);
You're attempting to assign a String to an int which the 2 of which are incompatible. You can get the ascii value of a single character
int ascii = testi.charAt(0);
You cannot convert string to ascii like that. You can convert a character to ascii
int ascii = (int)some_char;
First of all: Java doesn't use ASCII. It use Unicode (UTF-16, most of the time).
Second: You can make a function to convert your String characters to their Unicode representations, like this:
public static int[] convert(String str) {
int[] result = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
result[i] = str.charAt(i);
}
return result;
}
I am trying to get a string of charAt values from an entered string without using arrays.
Here is what I have so far:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str = "";
String encrypt = "";
int encry = 0;
int i = 0;
System.out.printf("Please enter a string: ");
str = input.nextLine();
int length = str.length();
System.out.println();
while (length <= length-1)
encry = str.charAt(++i);
System.out.println(encry);
Using what you've already achieved, I made an encryption method. I've also added a decryption method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("Please enter a string: ");
String message = input.nextLine();
String encryptedMessage = encrypt(message);
System.out.println(encryptedMessage);
System.out.println(decrypt(encryptedMessage));
input.close();
}
public static String encrypt(String message) {
String encrypted = "";
int i = 0;
int length = message.length();
while (i < length) {
int ascii = message.charAt(i++);
encrypted += " " + ascii;
}
return encrypted.trim();
}
private static String decrypt(String encryptedMessage) {
Scanner scanner = new Scanner(encryptedMessage);
String decryptedMessage = "";
while(scanner.hasNext()) {
decryptedMessage += (char) scanner.nextInt();
}
scanner.close();
return decryptedMessage;
}
Challenge
In the above code, the encrypted message has spaces in between each set of integers that represents a character. Taking one glance at the encrypted message, it's pretty easy to see that you just converted each character to its ASCII equivalent.
Instead of a space, try inserting a non-numerical character between the ASCII codes. Then, in the decryption method, use Scanner#useDelimiter to that character in order to retrieve the ASCII values.
while-condition should be something like (i<liength)
Block-brackets {} missing for the while.
Indexing starts with 0, thus it should be str.charAt(i++); instead of str.charAt(++i);.
The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.
I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.
From the docs for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Use nextLine instead. You can also print the line for debugging:
System.out.println(str);
Use String str = input.nextLine(); instead of String str = input.next();
This is the way you should do to get the next string.
You could have checked that str has the wrong value.