Using scan.nextLine() for Cyrillic - java

I don't know how to read Cyrillic or any other language except English from the console. I tried to do this:
Scanner scan = new Scanner(System.in, "UTF_16");
String input = scan.nextLine();
But it keeps waiting for me to enter even though I already entered the text.

You need to replace the UTF_16 by UTF-8...
public static void main(String args[]) {
Scanner scan = new Scanner(System.in, "UTF-8");
String input = scan.nextLine();
String myString = "some cyrillic text";
byte[] russianBytes = input.getBytes("ISO-8859-1");
String valueConverted = new String(russianBytes, "UTF-8");
System.out.println(valueConverted);
}
this print takes Илия Камбуров and print it properly

Related

How to convert a body of text to a single line string in Java?

I would like to convert a body of text which is in a form similar to this:
text here
text there
text everywhere
into a single string which would look like the following:
textheretexttheretexteverywhere
EDIT: The text on multiple lines is to be copied from one file and pasted into the input of the program, however it isn't necessarily a .txt file.
Here's what I have so far:
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","").replaceAll("\\\\n+", "");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
Here is my main function where I am calling my converter method:
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
String originalString = input.nextLine();
System.out.println("Original string: " + originalString);
converter(originalString);
}
Many thanks in advance!
(I'm new to programming so sorry if I'm missing something really obvious, I've tried everything I could find on Stack overflow)
Try this:
String line = "";
File f = new File("Path to your file");
FileReader reader = new FileReader(f)
BufferedReader br = new BufferedReader(reader);
String str = "";
while((line = br.readlLine())!=null)
{
str += line;
}
System.out.println(str);
for spaces:
str = StringUtils.replace(str," ","");
You pretty much got it! The only thing you are "missing" is that you added the extra .replaceAll when you didn't need to.
Also, it sounds like you may have different types of input, but here is a solution based on your code:
EDIT: Here is the solution below:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<> ();
String line = null;
while (!(line = input.nextLine()).isEmpty()) {
lines.add(line);
}
StringBuilder myOriginalString = new StringBuilder();
for (String s : lines) {
myOriginalString.append(s);
myOriginalString.append(" ");
myOriginalString.append("\n");
}
String originalString = myOriginalString.toString();
System.out.println("Original string: \n" + originalString);
converter(originalString);
}
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
}
Output:
Enter string:
text here
text there
text everywhere
Original string:
text here
text there
text everywhere
Refined string: textheretexttheretexteverywhere
Process finished with exit code 0
I did my best to model it around the type of input you would be giving. Based on your question, I assume you would be copying and pasting text to the prompt when you run your program. If you are looking to read from a file, then Mahbubur Rahman's answer is correct (and I won't replicate it in this answer as he deserves the credit.)
This should work.
String list = "text here\n";
list += "text there\n";
list += "text everywhere\n";
System.out.println("Original :\n"+list);
list= list.replace("\n", "").replace(" ", "");
System.out.println("New :\n"+list);

How to input text in java using the comand console?

I would like to input a copied text from a text processor or others.
Using nextLine() just introduces the first line and it doesn't let me use StringBuffer too. I haven't found anything to solve my problem.
This is my code:
public static void main (String args[]) {
Scanner keyboard= new Scanner(System.in);
StringBuffer lines= new StringBuffer();
String line;
System.out.println("texto:");
line= keyboard.nextLine();
//lines= keyboard.nextLine(); //this doesn´t work
System.out.println(lines);
}
Here is an example of what I would like to do:
I copy this text from a text file:
ksjhbgkkg
sjdjjnsfj
sdfjfjjjk
Then, I paste it on the cmd (I use Geany).
I would like to be able to get a StringBuffer or similar (something I can manipulate) like this:
StringBuffer x = "ksjhbgkkgsjdjjnsfjsdfjfjjjk"
Thanks!
Try using something like:
while(keyboard.hasNextLine()) {
line = keyboard.nextLine();
}
You could then store those lines. (e.g. an array/ArrayList).
You can append the keyboard.nextLine() to your stringBuffer like so:
lines.append(keyboard.nextLine());
StringBuffer will accept a String to be appended so this should fit your purposes.
You could use this with the while loop as shown by #Cache which would give something like:
while (keyboard.hasNextLine()) {
lines.append(keyboard.nextLine());
}
#Cache Staheli has the right approach. To elaborate on how you can put the keyboard input into your StringBuffer, consider this:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuffer lines= new StringBuffer();
String line;
System.out.println("texto:");
while(keyboard.hasNextLine() ) { // while there are more lines to read
line = keyboard.nextLine(); // read the next line
if(line.equals("")) { // if the user entered nothing (i.e. just pressed Enter)
break; // break out of the input loop
}
lines.append(line); // otherwise append the line to the StringBuffer
}
System.out.println(lines); // print the lines that were entered
keyboard.close(); // and close the Scanner
}

How can i make string save into a text file only if it starts with !test?

try {
Scanner Majora = new Scanner(System.in);
System.out.println("what is your name?");
String Link = Majora.nextLine();
Scanner Lenk = new Scanner(System.in);
System.out.println("name of file?");
String Lunk = Lenk.nextLine();
if(Link.equalsIgnoreCase("!addcom");
File ocarina = new File("/Users/Unknown/Desktop/commands/" + Lunk + ".txt");
if (ocarina.exists()) {
ocarina.createNewFile();
}
FileWriter Majoras = new FileWriter(ocarina.getAbsoluteFile());
BufferedWriter Zelda = new BufferedWriter(Majoras);
Zelda.write(Link);
Zelda.close();
}
this is what i got so far :/
i need help on making it like if a certain word is used before the string you wanna save. save the string.
use startswith string method
if(Link.startsWith("!test"))
Zelda.write(Link);
substring will get you the string without !test which is 5 characters
Link = Link.substring(5);

Why doesn't my program recognize the last names properly?

The scanner reads the wrong data, the text file format is:
111,Smith,Sam, 40,10.50
330,Jones,Jennifer,30,10.00
The program is:
public class P3 {
public static void main(String[] args) {
String file=args[0];
File fileName = new File(file);
try {
Scanner sc = new Scanner(fileName).useDelimiter(", ");
while (sc.hasNextLine()) {
if (sc.hasNextInt( ) ){ int id = sc.nextInt();}
String lastName = sc.next();
String firstName = sc.next();
if (sc.hasNextInt( ) ){ int hours = sc.nextInt(); }
if (sc.hasNextFloat()){ float payRate=sc.nextFloat(); }
System.out.println(firstName);
}
sc.close();
} catch(FileNotFoundException e) {
System.out.println("Can't open file "
+ fileName + " ");
}
}
}
The output is:
40,10.50
330,Jones,Jennifer,30,10.00
It is supposed to be:
Sam
Jennifer
How do I fix it?
The problem is that your data isn't just delimited by commas. It is also delimited by line-endings, and also by Unicode character U+FF0C (FULLWIDTH COMMA).
I took your code, replaced the line
Scanner sc = new Scanner(fileName).useDelimiter(", ");
with
Scanner sc = new Scanner(fileName, "UTF-8").useDelimiter(", |\r\n|\n|\uff0c");
and then ran it. It produced the output it was supposed to.
The text , |\r\n|\n|\uff0c is a regular expression that matches either:
a comma followed by a space,
a carriage-return (\r) followed by a newline (\n),
a newline on its own,
a Unicode full-width comma (\uff0c).
These are the characters we want to delimit the text by. I've specified both types of line-ending as I'm not sure which line-endings your file uses.
I've also set the scanner to use the UTF-8 encoding when reading from the file. I don't know whether that will make a difference for you, but on my system UTF-8 isn't the default encoding so I needed to specify it.
First, please swap fileName and file. Next, I suggest you use a try-with-resources. Your variables need to be at a common scope if you intend to use them. Finally, when using hasNextLine() I would then call nextLine and you can split on optional white space and comma. That could look something like
String fileName = // ...
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] arr = line.split("\\s*,\\s*");
int id = Integer.parseInt(arr[0]);
String lastName = arr[1];
String firstName = arr[2];
int hours = Integer.parseInt(arr[3]);
float payRate = Float.parseFloat(arr[4]);
System.out.println(firstName);
}
} catch (FileNotFoundException e) {
System.out.println("Can't open file " + fileName + " ");
e.printStackTrace();
}

how to give a string from user having space between it?

I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");
You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}
Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");

Categories

Resources