scanner does not work when I push enter - java

I am using java and I have a code as follow:
Scanner scanner = new Scanner(System.in);
while (true) {
String token = scanner.next();
if (token.equals("$")) break;
if (token.equals("(")) do sth;
else if (token.equals(")")) do sth;
else {
do sth
}
}
as you can see in the above code if you enter sth in the console then you enter $ at the end then the program will understand the end of input and the scanner can succesfully get each word of the string succesfully but instead I want when the user push enter then the scanner grabs the whole string and start reading it word by word I tried it this way :
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String token = scanner.next();
if (token.equals("(")) builder.buildOpenBracket();
else if (token.equals(")")) builder.buildCloseBracket();
else {
int number = Integer.parseInt(token);
builder.buildElement(number);
}
}
but now the proram runs forever and nothing happends

Firstly, to read new line and save it in a String you should use .nextLine()

Anyway I fixed it this way:
Scanner scanner = new Scanner(System.in);
String token = scanner.nextLine();
Scanner scannerToken = new Scanner(token);
while (scannerToken.hasNext()) {
String statement = scannerToken.next();
if (statement.equals("("))
else if (statement.equals(")"))
else {
}
}

Related

how to terminate an infinite console loop by letting the user press a specific key on the keyboard in java?

hi guys so as you can see it is an infinite loop
and I am asking if I could assign a key on the keyboard that terminates and stops this loop whenever the user presses this key.
NOTE that I am trying to do that in the console, not a UI
do{
//some calculations here
}while(true);
```
Two examples of doing what you want:
First example:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
} while(!input.equalsIgnoreCase("x"));
sc.close();
Second example:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
if (input.equalsIgnoreCase("x")) {
break;
}
} while(true);
sc.close();
Add your console code to the while-loop; press 'a' or 'A' to exit.
Scanner sc = new Scanner(System.in);
//Type in "a" to end
while (!sc.next().equalsIgnoreCase("a")) {
// console code here
}
System.out.println("Exiting");

Java: How do I make my program print without two extra dots?

This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}
Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}
I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));
Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}
You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs

catch block is running multiple times for InputMismatchException

So I was using this code in my program and whenever I give input consisting of multiple words, the compiler executes the catch block that many times. I've also tried it with different methods & till now all efforts went to vain.
Method 1:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
size = scanner.nextInt();
break;
}
catch (InputMismatchException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
Method 2:
Scanner scanner = new Scanner(System.in);
int size = 0;
boolean bError = true;
while (bError)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
bError = false;
}
Method 3:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
if (scanner.hasNextInt())
size = scanner.nextInt();
else
{
scanner.next();
System.out.println("Enter valid input (Digit Only)");
continue;
}
String sizeStr = Integer.toString(size);
Pattern pattern = Pattern.compile(new String ("^[0-9]*$"));
Matcher matcher = pattern.matcher(sizeStr);
if(matcher.matches())
{
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
continue;
}
}
Method 4:
Scanner scanner = new Scanner(System.in);
int size = 0;
while (scanner.hasNext())
{
if (scanner.hasNextInt())
{
size = scanner.nextInt();
System.out.println(size);
break;
}
else
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
}
}
I'm now able to do the task via taking a String input and then parsing it to int. But the initial doubt still remains that why that was not working properly. The code below is working fine.
Scanner scanner = new Scanner(System.in);
int size = 0;
while (true)
{
try
{
String sizeStr = scanner.nextLine();
size = Integer.parseInt(sizeStr);
break;
}
catch (NumberFormatException e)
{
System.out.println("Enter valid input (Digit Only)");
scanner.next();
continue;
}
}
According to the official Java Doc (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html):
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
The scanner can also use delimiters other than whitespace.
By default, all the next*() functions of scanner class other than nextLine() read the next token, not the next line. This means it reads until it finds a whitespace. If you want to read all the tokens in a line, you need to use nextLine() and then format the input explicitly as you want.
Consider this input:
abcd xyz
When you do scanner.nextInt() or any of scanner.next*() functions other than scanner.nextLine(), only "abcd" is read because it is the next token. When you do scanner.nextLine(), the complete string in the current line "abcd xyz" is read and the scanner advances to the next line.
However, if you want the nextInt() function to read the whole line, then you can set the delimiter to be new line '\n'.
Scanner scan = new Scanner(System.in).useDelimiter("\n");
Using this, you can get the behaviour that you want.

Sanitizing user input in Java, correcting mistakes [duplicate]

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

java find a specific line in a file based on the first word

I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}

Categories

Resources