Read a multi-word string from stdin - java

I want to read multiple words into a string called input. The words can be casted into numeric values like "1 14 5 9 13". After the user input, the string will be converted into a string array separated by spaces.
public class ArraySum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.next());
System.out.println("Please enter "+n+" numbers");
String input = scanner.next(); // ERROR: only the first word is read
String[] inputs = input.split("\\s+");
int sum=0;
for (int i =0; i<inputs.length; i++){
if (!inputs[i].equals(""))
sum+= Long.parseLong(inputs[i]);
}
System.out.print(sum);
}
}
However only the first word is read into the string.
This answer suggests using nextLine() to read a multi-word string, but if I change it, an error was thrown.
java.lang.NumberFormatException: null
Apparently an empty/null string was inputted before I entered any word.

You have to use nextLine after nextInt to clear your Scanner like this :
int n = scanner.nextInt();//read your int
scanner.nextLine();//clear your Scanner
System.out.println("Please enter " + n + " numbers");
String input = scanner.nextLine();//read your String example 12 55 66

Related

save several names in a string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.

java scanner get data and detected enter each numbers and characters

I'm a beginner to the Java language. Firstly I want use a Scanner to retrieve data
For example, I enter this: 990921205 v
How can I detect the first 2 numbers for any calculation?
How can I detect each numbers for an algorithm?
I tried this:
import java.util.Scanner;
class ID2 {
public static void main(String args[]){
Scanner in=new Scanner (System.in);
int num[]=new int[3];
int A=0;
int B=0;
int C=0;
System.out.println("enter a number " +A);
}
}
With next() method of Scanner you can obtain user standard input.
String userInput = in.next();
int first = Integer.parseInt(userInput.charAt(0));
int second = Integer.parseInt(userInput.charAt(1));
//DO STUFF
Well to get the inputted values you can use Scanner.next(), but if this inputted value is an int you can also use Scanner.nextInt() to read it as an integer:
int value1= in.nextInt();
Then you will have an integer in the value1 value.
But if you are entering a string you will use the Scanner.next()to get this string and then extract the first two elements:
String s=in.next();
int firstTwoval=Integer.parseInt(s.substring(0, 2));
The answer #bigdestroyer gives this error: The method parseInt(String) in the type Integer is not applicable for the arguments (char)
You can just do it with char and not with integers at all.
For example,
Scanner input = new Scanner(System.in);
String numInput = input.next();
char nums[] = new char[numInput.length()];
for (int i = 0;i < numInput.length(); i++){
nums[i] = numInput.charAt(i);
System.out.println("For nums["+i+"] : "+nums[i]);
}
Input:
0123456789
Output:
For nums[0] : 0
For nums[1] : 1
For nums[2] : 2
For nums[3] : 3
For nums[4] : 4
For nums[5] : 5
For nums[6] : 6
For nums[7] : 7
For nums[8] : 8
For nums[9] : 9
Now since you want the first 2,3,4++ digits, you can apply the answer #chsdk gave.
If you use mine you have to parse them to integer using Integer.parseInt() to be sure that it's an actual number.

How to pause "for" in Java so that I can input some text

I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand

How to limit the input to the Scanner?

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = checkInput(in, "Enter an integer and a base: ");
int inputBase = checkInput(in, "");
}
public static int checkInput(Scanner in, String prompt) {
System.out.print(prompt);
while (!in.hasNextInt()) {
in.next();
System.out.println("Sorry, that is an invalid input.");
System.out.print(prompt);
}
return in.nextInt();
}
This method works and doesn't return any bad input i.e., ; p "hello".
My question is how can I limit the number of inputs the scanner will read. Say I input 5 five % ; but I only want 5 and five to be passed in to my method and the rest dropped.
I looked through the Java API but couldn't find a method that would limit the amount of user input accepted. Am I just missing it or is there another way to do this?
Edit: I have tried using the .length() method to limit the input but then that doesn't allow integers greater than the .length() parameter.
Here is a working sample of how you could accomplish what you need. I broke it up so that the user is prompted once for each input which makes it easier to validate. I changed your checkInput method to getInput which only returns valid user input as a String where it is then converted into an int.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inputInt = Integer.parseInt(getInput(in, "Enter an integer: "));
int inputBase = Integer.parseInt(getInput(in, "Enter a base: "));
System.out.println("Int: " + inputInt + ", base: " + inputBase);
}
public static String getInput(Scanner in, String prompt) { // Get valid user input
System.out.print(prompt); // Tell user what to input
String text = "";
while (true) { // Keep looping until valid input is found
text = in.nextLine(); // Get input from stdin
if(isInteger(text)) // Check if they put in integer
break; // Exit loop
System.out.print("Try again, " + prompt); // Wasn't valid, prompt again
}
return text; // Return valid user input
}
private static boolean isInteger(String str) { // Check if string is integer
try {
Integer.parseInt(str); // If this doesn't fail then it's integer
return true;
} catch(NumberFormatException e) {
return false; // Wasn't integer
}
}
Sample run:
Enter an integer: 2 dog five 3
Try again, Enter an integer: 2
Enter a base: cat
Try again, Enter a base: 3
Int: 2, base: 3
It helps to separate functionality - you were trying to read input, validate input, and convert to int all in one method. If you break it up it becomes easier to manage.
Scanner sc= new Scanner(System.in);
String string = sc.findInLine(".{500}"); // length of your input you want
findInLine(String pattern)
method of Scanner class of java.util package. This method returns a String object that satisfies the pattern specified as method argument.
see this article
If you want to only get the first two words (or strings delimited by spaces) you can use the str.split(" "); method.
For example:
String input = in.nextLine(); // Gets the next line the user enters (as a String)
String[] inputWords = input.split(" "); // inputWords[0] is first word, inputWords[1]
// is second word... etc
String validInput = inputWords[0] + " " + inputWords[1]; // Combines the first and
// second words into a string, so if you had "5 five %" validInput would be "5 five"
// inputWords[0] is "5", inputWords[1] is "five", inputWords[3] is "%" etc for any other words...
This will essentially limit the number of inputs to two words. I hope this helps!
Scanner scan = new Scanner(System.in);
System.out.println ("enter a 2 numbers");
String s;
s = scan.nextLine();
Scanner scan2 = new Scanner(s);
int one = scan2.nextInt();
int two = scan2.nextInt();
System.out.println (" int 1 = " + one + " int 2 = " + two);
enter a 2 numbers
23 45 68 96 45
int 1 = 23 int 2 = 45
Process completed.

Categories

Resources