I have to read the following symbols with Scanner and process them separately.
The input is:
###xx#*
1 -1 -1 4
The first line is the life and food of a game animal, the second row are her moves the - to the left, + to the right
I start with something, but not enough:
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
System.out.print("[" + ch + "] "); // to check what is happening
}
How to read the second row of integers with - and + and then operate with them?
You can use Scanner 's built-in methods like nextInt() and next() also look for something like hasNextInt() it can be usefull.
You can use various scanner class functions to do that. Input is:
1 -1 -1 4
Create two arrays to store characters '-' and '+' and one to store integers
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
if(sc.hasNextInt()){
intArray = sc.nextInt();
}
else charArray = sc.next();
}
You can parse the input character to integer if it parses then you can continue your code if it throws number format exception then you should know input character is not a number.
Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
while (!sc.hasNext("z")) {
char ch = sc.next().charAt(0);
try {
int a = Integer.parseInt(String.valueOf(ch));
switch (a){
case 1:
// your condition
case -1:
// your condition
case -4:
//condition
default:
// your condition
}
}catch (NumberFormatException ex){
System.out.printf("input character is not number");
}
System.out.print("[" + ch + "] ");// to chack what is happening
}
The Java Scanner class has a whole bunch of methods for grabbing and parsing the next part of a string, e.g. next(), nextInt(), nextDouble(), etc.
The code looks like this:
String input = "1 -1 -1 4";
Scanner s = new Scanner(input);
int i1 = s.nextInt();
int i2 = s.nextInt();
int i3 = s.nextInt();
int i4 = s.nextInt();
Will read all four values
as most of the people is saying you can use scanner.nextInt() and about watching if you have to go the left or to the right you have the method Math.signum() which tells you were to go and then you can take the Math.abs() to get the value as an absolute number.
You could read whole line instead read by characters. Then split line into String array which will be contains chars of lines and operate with array. Here the solution of your case line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("z")) {
String line = sc.nextLine();
String[] split = line.replaceAll("(-*[\\W\\d\\w])(\\s*)", "$1 ").trim().split(" ");
Arrays.asList(split).forEach(ch -> System.out.print(ch + " "));
}
}
Output:
###xx#*
# # # x x # *
1 -1 -1 4
1 -1 -1 4
Related
Scanner input = new Scanner(System.in)
System.out.print("Enter either a string or a number");
String str = input.nextLine();
int x = input.nextInt();
The program here expects 2 values, a string and an integer. YET there is only one.
I want str to register the value if it is a string, BUT if it is an integer, I want the value to be registered by x
In other words, I only want one of the variables to be active
if the value of entered is an integer, then you can simply use regex where
if(str.matches("\\d+") || str.matches("-\\d+"))
checks if the entered number is a number of 1 or more digits or the entered number is a negative number with one or more digits
and if that is the case, then you can x = Integer.parseInt(str); to convert that entered string into integer and make str = ""; otherwise , the entered string is stored in str and never parsed to int
and this is the edited code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter either a string or a number\n");
String str = input.nextLine();
int x = 0;
if(str.matches("\\d+") || str.matches("-\\d+"))
{
x = Integer.parseInt(str);
str = "";
}
else
{
// nothing to do
}
System.out.println("x = " + x);
System.out.println("str = " + str);
}
}
and this is some example output:
Enter either a string or a number
10
x = 10
str =
Enter either a string or a number
test
x = 0
str = test
Enter either a string or a number
-30
x = -30
str =
Enter either a string or a number
test10
x = 0
str = test10
The answer provided by abdo and the comment by Jesse are both valid and very good answers.
However it is also possible to achieve your goal with the Scanner methods. In this case hasNextInt() is your friend.
f
But note, that nextLine() will consume the line break, while nextInt() will not. IMHO it will be more clear to code both options alike and use next() instead.
The most simple approach:
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine(); // consume the line break, too
Here still one issue remains: By default Scanner uses whitespace as delimiter, not line breaks. With the input "4 2\n" nextInt() will return 4 and nextLine() will discard the rest. However the user's intention (number versus string) is not obvious in this case either, therefor I'd tend to create the string "4 2" instead. This can easily be achieved by using line breaks as delimiter instead:
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
A full demo example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter(System.lineSeparator());
System.out.println("Enter either a string or a number");
String str = null;
while (!"end".equals(str)) {
int x = 0;
str = null;
if (input.hasNextInt()) {
x = input.nextInt();
}
else {
str = input.next();
}
input.nextLine();
if (str != null) {
System.out.printf("we have a string! str=%s%n", str);
}
else {
System.out.printf("we have a number! x=%d%n", x);
}
}
System.out.println("goodbye!");
}
}
I wrote a code about result for operator input taken by user and please explain me how this character input work because when i was using
char operation = s.nextLine().charAt(0);
instead of
char operation = s.next().charAt(0);
Eclipse showed Error.
Code -
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
char operation = s.next().charAt(0);
int result = 0;
switch (operation) {
case '+' :
result = a + b;
break;
case '-' :
result = a - b;
break;
case '*' :
result = a * b;
break;
case '/' :
result = a / b;
break;
case '%' :
result = a % b;
break;
default:
System.out.println("Invalid Operator!");
}
System.out.println(result);
s.close();
}
}
The problem is not because of s.nextLine(); rather, it is because of s.nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Use
int a = Integer.parseInt(s.nextLine());
instead of
int a = s.nextInt();
I would recommend you create a utility function e.g. getInteger as created in this answer to deal with exceptional scenarios as well.
From the documentation of Scanner https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
So if you put .nextLine() you're in fact reading what has left since the last input to the next line (ie nothing). This can be demonstrated with this code
Scanner s = new Scanner(System.in);
System.out.println("Enter First Number:");
int a = s.nextInt();
System.out.println("Enter Second Number:");
int b = s.nextInt();
System.out.println("Which Operation you want to execute?");
s.hasNextLine();
String s1 = s.nextLine();
String s2 = s.nextLine();
System.out.println(s1);
System.out.println(s2);
//char operation = s1.charAt(0); -> error
char operation = s2.charAt(0);//operator is read
The first print (s1) will not print anything. The second will print the operator.
I cannot get out of while loop.
I do not why sc.hasNextInt() does not return false after last read number.
Should I use another method or is there a mistake in my code?
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int[] numbers = new int[sc.nextInt()];
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
**while ( sc.hasNextInt()) {**
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
}
Do the following:
Use the input length as the end of the loop.
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int len = sc.nextInt();
int[] numbers = new int[len]; // use len here
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
for (index = 0; index < len; index++) { // and use len here
numbers[index] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
And don't close the scanner.
When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:
You submit a non-numeric symbol (e.g. a letter).
You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.
Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.
However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:
String s = "Hello World! 3 + 3.0 = 6 ";
We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):
Scanner scanner = new Scanner(s);
Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Found int value: " + scanner.next());
} else {
scanner.next();
}
}
Result:
Found int value: 3
Found int value: 6
In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).
However, we could use while (hasNextInt()) to read the list of numbers from a file.
Now, the solution to your problem would be to place the index variable inside the while loop condition:
while (index < numbers.length) {
numbers[index++] = sc.nextInt();
}
Or for clarity`s sake, make a specific counter variable:
int index = 0;
int counter = 0;
while (counter < numbers.length) {
numbers[index++] = sc.nextInt();
counter++;
}
I've looked through everything relevant I can find on here, but for some reason nothing is helping. Whenever I run this I always end up with a result of 0. And no, I can not use other libraries for this (I saw some awesome solutions that have it down to one line, but I can't do that)
public void process()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your String:");
String in_string = input.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("Press 1 to count the occurrence of a particular letter.");
System.out.println("Press 2 to count the total words in your input sentance.");
System.out.println("Press 3 to change your input sentance.");
System.out.println("Press 4 to exit.");
int option = input2.nextInt();
if (option==1)
{
System.out.println("Choose your letter: ");
String in_occurence = input.nextLine();
for(int i = 0 ; i < in_string.length(); i++)
{
if(in_occurence.equals(in_string.charAt(i)))
{
charCount++;
}
}
System.out.println(charCount);
}
You are comparing a String with a char using String#equals(). That will always give you false.
For example:
System.out.println("a".equals('a')); // false
You should convert the String to char by getting character at index 0 before comparison:
if(in_occurence.charAt(0) == in_string.charAt(i))
or, just declare in_occurrence as char type:
char in_occurence = input.nextLine().charAt(0);
You are comparing a String to a char which is never equal even if the String contains that char.
What you want is
if (in_occurance.charAt(0) == in_string.charAt(i)) // compare char
I'm trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play another round or not. Problem is, the program always skips the last question (never letting the user answer 'y' or otherwise. What am I missing here? Is there something about java.util.Scanner I don't know about?
import java.util.Random;
import java.util.Scanner;
public class GuessNum {
public GuessNum() {
int numRandom = 0;
int numGuess;
int life = 5;
String want = "";
Random rand = new Random();
Scanner scan = new Scanner(System.in);
do {
int lifeLeft = 5;
numRandom = rand.nextInt(9)+1;
System.out.print("\nGuess the Number [1..10]\n");
System.out.print("===================\n");
System.out.print("You have " + lifeLeft + " chances.\n");
do {
do {
System.out.print("What number do I have in mind: ");
numGuess = scan.nextInt();
if (numGuess < 1 || numGuess > 10)
System.out.println("Invalid input. Range is 1-10.");
} while (numGuess < 1 || numGuess > 10);
if (numGuess != numRandom && lifeLeft != 0)
System.out.println("Wrong! You only have " + --lifeLeft + " chances left.");
} while (numGuess!=numRandom && lifeLeft > 0);
if (numGuess == numRandom)
System.out.println("Correct! -- in " + (life - lifeLeft) + " guess(es).");
if (lifeLeft == 0) {
System.out.println("You have no more lives..");
System.out.println("This is the number: " + numRandom);
}
System.out.print("\nEnter 'y' if you want to play again or any other character to exit: ");
want = scan.nextLine();
} while (want.equals("y") || want.equals("Y"));
}
public static void main(String[] args) {
new GuessNum();
}
}
Use want = scan.next(); instead of nextLine().
The reason for your problem is that following the preceding nextInt(), you're still on the same line, and nextLine() returns the rest of the current line.
Here's a smallest snippet to reproduce the behavior:
Scanner sc = new Scanner(System.in);
System.out.println("nextInt() = " + sc.nextInt());
System.out.println("nextLine() = " + sc.nextLine());
When you type in, say, 5 and then hit Enter, the output is:
nextInt() = 5
nextLine() =
That is, nextLine() did not block for your input, because the current line still has an empty string remaining.
For comparison, when you type in, say 5 yeah! and then hit Enter, then the output is:
nextInt() = 5
nextLine() = yeah!
Note that " yeah!" actually comes from the same line as the 5. This is exactly as specified in the documentation:
String nextLine(): Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
On half-open ranges
Assuming that the number to guess is between 1 and 10 inclusive, the following code is "wrong":
numRandom = rand.nextInt(9)+1; // this can only be in 1..9 range inclusive!
Here's an excerpt from the documentation of java.util.Random:
int nextInt(int n): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
That is, like a lot of methods in Java's API, Random.nextInt(int) uses the half-open range, with inclusive lower bound and exclusive upper bound.
Related questions
Are upper bounds of indexed ranges always assumed to be exclusive?
Use scan.next()+ scan.nextLine(); instead
eg.
Scanner scan = new Scanner(System.in);
String s = scan.nextLine() +scan.nextLine();
Problem occurs because the last newline character for the last line of input is still queued in the input buffer and the next nextLine() will be reading the remainder of the line (which is empty).
So, when you use next it goes to the next token, then you can get the remaining input using nextLine()