Java string with enter

How to take a string with blank spaces as input in Java

In this post, we will learn how to take a string with blank spaces as input in Java. We will use the next() and nextLine() methods to read the strings with blank spaces.

next() and nextLine() methods of the Scanner class:

The next() and nextLine() methods of the Scanner class can be used to read user inputs from the console. We can use any of these methods to read the user input.

But there is a difference between the next() and nextLine() method. The next() method can read strings up to the space. For example, if you use the next() method to read the string Hello World, it will read only the Hello word. It will stop if it finds any blank space.

But, we can use the nextLine() method to read a string with blank spaces. It will read the whole Hello World string. The nextLine() method stops if it reads a newline character \n or if the user press the enter key.

So, if you want to take a string with blank spaces as input from the console, you have to use the newLine() method.

Читайте также:  Ошибка python invalid continuation byte

Let’s take a look at the below example:

import java.util.Scanner; public class Example1  public static void main(String[] args)  try (Scanner sc = new Scanner(System.in))  String str; System.out.println("Enter a string: "); str = sc.nextLine(); System.out.println("You have entered: " + str); > > >
  • We have created one Scanner object sc to read the user input.
  • It asks the user to enter a string.
  • It uses the nextLine() method to read the user input string and assigns it to the str variable.
  • The last line is printing the str variable.

If you run this program, it will print output as below:

Enter a string: Hello World You have entered: Hello World

Java read strings with spaces

Let’s try with the next() method. If you use this method, it will not read the blank spaces.

import java.util.Scanner; public class Example2  public static void main(String[] args)  try (Scanner sc = new Scanner(System.in))  String str; System.out.println("Enter a string: "); str = sc.next(); System.out.println("You have entered: " + str); > > >

If you run this program, it will print:

Enter a string: Hello World You have entered: Hello

How to use the next() method to read a string with blank spaces:

We can also use the next() method to read a string with blank spaces. We can set the scanner’s delimiting pattern with the useDelimiter method. It takes the pattern as the parameter. If we pass «\n» as the parameter, it will read the string up to the new line.

import java.util.Scanner; public class Example3  public static void main(String[] args)  try (Scanner sc = new Scanner(System.in).useDelimiter("\n"))  String str; System.out.println("Enter a string: "); str = sc.next(); System.out.println("You have entered: " + str); > > >

If you run this program, it will print output similar to the example of nextLine() :

Enter a string: Hello World You have entered: Hello World

Источник

How to Press Enter into File in Java [duplicate]

For instance, in Windows is , in current Macs and Linux is and in older Macs is . Solution 1: In java, «enters» are considered new lines.

How to Press Enter into File in Java [duplicate]

Possible Duplicate:
Java: How do I get a platform independent new line character?

I want to write enter into file with class RandomFileAccess , but I can’t do it properly.

char enter = '\n' ; outputfile.writeChar(enter); 

I’m Using Windows. Thanks for your help but it didn’t work 🙁

I expected this Style of File :

I t ‘ s B e f o r e E n t e r . . . I t m u s t b e o n n e x t L i n e . . .

Use System.getProperty(«line.separator»); instead new line character.

Sequence used by operating system to separate lines in text files

What operating system are you using? Better use this:

String enter = System.getProperty("line.separator"); 

Using the above snippet, you won’t have to worry about the exact details of line breaks, because they change depending on the operating system currently in use.

For instance, in Windows is \r\n , in current Macs and Linux is \n and in older Macs is \r .

How to Press Enter into File in Java, Better use this: String enter = System.getProperty («line.separator»); Using the above snippet, you won’t have to worry about the exact details of line breaks, because they change depending on the operating system currently in use. For instance, in Windows is \r\n, in current Macs and Linux is \n and in older … Usage exampleString enter = System.getProperty(«line.separator»);Feedback

Making an «enter» into a string in java

This may seem like a bit of a strange question, but I want to make an «enter» keystroke into a string. I made a rather basic program to scan my papers (that I write for school) to find things such as prepositions at the end of a sentence or contractions I may have accidentally added. My issue is, when i put the paper into my code, it try to tokenize all the sentences at periods. When it reaches the point where I hit «enter» to move to the next line, it breaks and stops tokenizing. I thought of maybe making «enter» into a string so that i could replace it with a space, but I can’t figure out how to get the effects of an «enter» into a string. Is there another way to stop the «enters» from breaking my code?

Sum up: I enter my paper into my code and the effects of hitting «enter» in the paper cause the code to err. I want to be able to enter the paper and have the code ignore the effects of the «enter.»

In java, «enters» are considered new lines. There are several ways to combat your problem. The most simple way is to compare each index of the string with the ‘\n’ char which denotes a new line.

Please post a sample code of your problem if the problem persists. It is easier to correct issues when someone can see exactly what you are doing.

I would not look for just \n\ or \r\n as the line feed can be different from computer to computer, especially with different OS.

I would use the System Properties to get the specified line feed you need:

String enterKey = System.getProperty("line.separator"); 

This gets the sequence used by operating system to separate lines in text files

Making an «enter» into a string in java, In java, «enters» are considered new lines. There are several ways to combat your problem. The most simple way is to compare each index of the string with the ‘\n’ char which denotes a new line. Please post a sample code of your problem if the problem persists.

Java — add Enter Button

I want to combine two Strings when I push the Enter-Button.

Also when I Tab from the TextField to the Button it works when i push Space but not with Enter. Is this normal for Java ?

(Comments are in German so you can just ignore them, if you don’t understand the language)

package demo; // Gehört zum Paket demo import java.awt.*; // Abstract Windows Toolkit importieren import java.awt.event.*; // Abstract Windows Toolkit Events importieren import javax.swing.*; // Swing importieren /** @author @version 1.0*/ public class strings extends JFrame implements ActionListener < // Klasse strings auf public gesetzt - erweitert mit JFrame - implementiert Action Listener JButton but1; // Indiziert Button (für GUI) JTextField tfstring; // Indiziert TextFeld (für GUI) JTextField tfstring2; // Indiziert TextFeld (für GUI) JTextField endstring; // Indiziert Ausgabefeld (für GUI) String str1; // Indiziert String String str2; // Indiziert String String fullstring; // Indiziert Ausgabe für beide Strings public strings() < // Konstrukt strings auf public gesetzt JFrame frame = new JFrame("Strings"); // Neues Fenster mit Titel (für GUI) JPanel Panel = new JPanel(); // Container erstellen JLabel label = new JLabel("Ihr String 1:"); // Text einfügen Panel.add(label); // Label in Pannel einfügen tfstring = new JTextField("", 15); // Textfeld erstellen (für GUI) Panel.add(tfstring); // Text Feld String in Panel einfügen JLabel label2 = new JLabel("Ihr String 2:"); // Textfeld erstellen (für GUI) Panel.add(label2); // Label in Panel einfügen tfstring2 = new JTextField("", 15); // Textfeld erstellen (für GUI) Panel.add(tfstring2); // Text Feld String in Panel einfügen but1 = new JButton("OK"); // Button erstellen but1.addActionListener(this); // Methode für den Button erstellt Panel.add(but1); // Button in Panel einfügen JLabel label3 = new JLabel("Fertiger String:"); // Ausgabefeld erstellt Panel.add(label3); // Label in Oannel ainfügen endstring = new JTextField("", 20); // textfeld für Ausgabe endstring.setEditable(false); // Sperrt Ausgabefeld Panel.add(endstring); // Fertiger String in Panel einfügen frame.add(Panel); // Panel hinzufügen frame.setSize(900,75); // Grösse des Fensters frame.setVisible(true); // Panel sichtbar machen frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Standart Operation beim Schliesen des Fensters erstellt >public static void main(String[] args) < // TODO Auto-generated method stub strings st = new strings(); // Konstruktor ins main einbinden >@Override public void actionPerformed(ActionEvent e) < // TODO Auto-generated method stub if(e.getSource() == this.but1)< // Methode für Button festlegen str1 = tfstring.getText(); // String 1 nimmt Text von tfstring str2 = tfstring2.getText(); // String 2 nimmt Text von tfstring 2 fullstring = str1 + str2; // Ausgabe beider Strings aus String 1 und String 2 zusammensetzen endstring.setText((fullstring)); // Fertiger String nimmt Text von der Ausgabe beider Strings >> > 

Add keylistener to your button but1 like that:

// declare the listener but1.addKeyListener(new KeyListener() < // listen to keys public void keyPressed(KeyEvent e)< // find ENTER key press if(e.getKeyCode() == KeyEvent.VK_ENTER)< // do your stuff here. :) >> > 

NOTE : if you want this action be performed in various elements like JTextField don’t declare the listener on the fly :

Declare the KeyListener like this:

KeyListener listener = new KeyListener() < // listen to keys public void keyPressed(KeyEvent e)< // find ENTER key press if(e.getKeyCode() == KeyEvent.VK_ENTER)< // do your stuff here. :) >> 

And add it to the elements you need:

but1.addKeyListener(listener); tfstring.addKeyListener(listener); 

If you want to add an «Enter Event», you have to add a KeyListener to the Textfield , listen for the Enter -Key and execute the same code, you’d execute when pushing the button.

Note: This is what you need to do, if you want to press Enter from the Textfield. So you don’t need to use Tab to switch to the Button

This is because of «Focus». You need to add KeyListener for TextFields.

@Override public void keyTyped(KeyEvent e) < recognizeKey(e); >@Override public void keyPressed(KeyEvent e) < recognizeKey(e); >@Override public void keyReleased(KeyEvent e) < recognizeKey(e); >public void recognizeKey(KeyEvent e) < int keyCode = e.getKeyCode(); switch(keyCode) < case KeyEvent.VK_ENTER: //TODO: do something break; default: //TODO: do something break; >> 

Input — Java using scanner enter key pressed, If the «enter» (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

(Java) How to get user input without pressing the «enter» key [duplicate]

I was curious and wanted to test this type of thing out in java. I looked it up online and couldn’t really find anything that helped out in any of the questions I found; so I decided to ask it myself.

In the example I wrote out, you’re given a couple of options and you get user input and then stuff happens based off of user input using a switch statement. Doesn’t really matter what happens as I’m trying to figure out how to get user input without having to press enter.

So, for example, if the user has to choose between 1, 2, 3, 4, or 5 for input, when the user presses ‘2’, for example, the program reads this input instantly without them having to press enter. Is there any way to do this? I’m using cmd on Windows 10 as well (thought about it when I was doing a project on NetBeans though, this shouldn’t make a difference I don’t think).

You need to run your program in some way that doesn’t line-buffer user input.

Lots of detail here and some related discussion here.

public static void main(String[] args) throws IOException

and a «Terminal» app on OS X with this:

behaves like this when run (where the above code is in a file named Scratch.java , and I typed a single A as input):

$ stty raw && java Scratch hit a key: 65 

You can do something like this:

import java.io.IOException; public class MainClass < public static void main(String[] args) < int inChar; System.out.println("Enter a Character:"); try < inChar = System.in.read(); System.out.print("You entered "); System.out.println(inChar); >catch (IOException e) < System.out.println("Error reading from user"); >> > 

will read the char that the user have been entered.

How to enter quotes in a Java string?, If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example: String theFirst = «Java Programming»; String ROM = «\»» + theFirst + «\»»; Or, if you want to do it with one String variable, it would be: String ROM = «Java Programming»; ROM = «\»» + ROM …

Источник

Как добавить перенос строки в Java

Перенос строки, он же перенос каретки это один или несколько спецсимволов, означающие окончание текущей строки символов и перевод картеки на новую строку. В зависимости от операционной системы используются разные спецсимволы. Например, в Windows используются спецсимволы CR + LF:

Спецсимолы Альт-код Управляющая последовательность Операционные системы
CR LF 13 10 \r \n DOS, OS/2, все версии Windows (в том числе и последние)
LF 10 \n Linux, macOS, Unix и прочие POSIX-совместимые системы
CR 13 \r Старые версии Mac OS (до версии 9)

Спецсимволу CR соответсвует альт-код 13, а спецсимволу LF альт-код 10. Кстати, CR означает carriage return (возврат каретки), а LF это line feed (перевод строки). Управляющая последовательность \r\n или \n как раз и обозначает перевод строки в Си подобных языках программирования.

Как сделать перенос строки

Допустим, у вас есть строка, содержимое которой выводится в консоль:

String oneLine = "Hello Java World!"; System.out.println(oneLine);

При выводе в консоль вы увидите те же слова, составляющие ровно одну строку, без переносов на новые строки. Как же нам добавить перенос строки в Java?

Для разных операционных систем переносом строки являются разные управляющие символы:
Для Windows это символы \r\n
Для Linux, macOS и прочих *nix систем это \n

Нужно добавить в искомую строку нужную управляющую последовательность, в зависимости от того, в какой операционной системе выолняется ваша программа.

Способ первый – захардкодить перенос строки

Допустим, ваша программа на Java запускается в Linux. Вы просто добавляете символы \n в то место в строке, в котором вам нужно сделать перевод на новую строку:

String multipleLines = "Hello\nJava\nWorld!"; System.out.println(multipleLines);

Теперь, при использовании переносов строки, вы, вместо одной строки в консоли увидите три строки – по каждой на символы \n

Но как же быть, если вы не хотите хардкодить символы переноса строки?

Способ второй – портабельный и правильный

Если вы не хотите писать символы \n каждый раз, когда хотите сделать перенос строки – вы можете воспользоваться стандартным методом System.lineSeparator() , который возвращает перенос строки для той операционной системы, в которой сейчас выполняется ваша программа. Это очень полезно, если программа исполняется и в Windows и в Linux окружении.

Просто используйте System.lineSeparator() в том месте, где вам нужно создать новую строку:

String multipleLines = "Hello" + System.lineSeparator() + "Java" + System.lineSeparator() + "World!"; System.out.println(multipleLines);

Итак, вы научились делать перевод строки в Java, используя два способа.

Источник

Оцените статью