I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}
Related
'''
Scanner sc = new Scanner(System.in);
ArrayList<Integer> arrayIntegers = new ArrayList<Integer>();
System.out.print("#ofints: ");
String[] arrayStrings = new String [sc.nextInt()];
sc.nextLine();
for (int i = 0; i < arrayStrings.length; i++)
{
arrayStrings[i] = sc.nextLine();
}
'''
-How can this be done with using hasNext() method (breaks if space is entered) so there is no need for user prompt statement.
so e.g.:
1
2
3
Instead of:
#ofints: 3
1
2
3
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default.
Check this (stop on enter "exit"):
Scanner sc = new Scanner(System.in);
String inputStr;
while (sc.hasNext()) {
inputStr = sc.next();
if (inputStr.equals("exit")) break;
System.out.println(inputStr);
}
P.S. The hasNextLine() method checks to see if there's another line in the input of the Scanner object, no matter if the line is blank or not.
I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.
This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?
Here is the relevant chunk of code from my little app.
//These variables used during input validation
String tempName;
int tempGrade;
//These regex patterns are for input validation
//Names can be 1-15 letters and grades are 2 digits
Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
Pattern gradePattern = Pattern.compile("[0-9]{2,2}");
//Parallel arrays to hold last names and grades
String[] names = new String[5];
int[] grades = new int[5];
Scanner in = new Scanner(System.in);
try {
for(int i = 0; i<5; i++) {
System.out.println("Enter a name:");
tempName = in.nextLine();
System.out.println("Enter a grade:");
tempGrade = in.nextInt();
in.nextLine();
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
}
names[i] = tempName;
grades[i] = tempGrade;
}
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
tempName = in.nextLine(); //<-- add this.
}
Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.
I am making a search engine to find what document matches the words given by the user. The following is my code:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
stringArray[i] = userInput.next();
i++;
}
for (int j = 0; j < i; j++){
System.out.println(stringArray[j]);
}
This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.
hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
while (i < stringArray.length
&& userInput.hasNextLine()
&& !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
i++;
}
for (int j = 0; j < i; j++) { // just for testing purposes
System.out.println(stringArray[j]);
}
But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for:");
List<String> stringList = new ArrayList<>();
String line;
while (userInput.hasNextLine()
&& !(line = userInput.nextLine().trim()).isEmpty()) {
stringList.add(line);
}
stringList.forEach(System.out::println); // just for testing purposes
Change your while loop to this:
while (!(String temp = userInput.nextLine()).trim().contentEquals("")) {
stringArray[i] = userInput.next();
i++;
}
String line;
int i = 0;
while(!(line = userInput.nextLine()).isEmpty()) {
for (String word :line.split("\\s+")){
stringArray[i]=word;
i++;
}
}
This code assigns every line from Scanner into variable line until is not user input empty. In every iteration it splits line to words and assigns to stringArray.
i need to read multiple lines from stdin in java.
For example i need to read this two lines:
A A A H
A E D A H
and give an answer for each line.
I have made this but i can stop the while
Scanner sc = new Scanner(System.in);
Posicao p;
int max[][] = new int[4][], j = 0;
String com;
String[] b;
char[] c;
while(sc.hasNextLine()){
p = new Posicao();
com = sc.nextLine();
b = com.split(" ");
c = new char [b.length];
for(int i = 0;i<b.length;i++) c[i] = b[i].charAt(0);
p.comando(c);
max[j++] = p.retorna();
}
if (com.isEmpty()) {
break;
}
You could check what the user inputs and exit on empty input or the word "exit":
/*This would go in your while loop, after you process the input*/
if (com.equals("") | com.equals("exit")) {
System.out.println("Exiting...");
break;
} else
System.out.println("Still in loop");
Ideally you need to modify this part while(sc.hasNextLine()) to break the loop. Do you know any of the below values?
Number of lines
Any special char using which you can find end of input
Read each line using Scanner.nextLine() method and use String.split() or StringTokenizer to read tokens from each line. (see the example below) :
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine())
{
String[] tokens = scanner.nextLine().split("\\s");
System.out.println(Arrays.toString(tokens));
}
scanner.close();}
same as thisquestion I want to get input from user while he/she give me strings. but the difference is that now before I get strings , I must get 26 numbers. so this code works wrong in getting myStrings. what should I do?
Wrong code:
for (int i = 97; i < 123; i++) {
alphabet[i] = scan.nextFloat();
}
String infix;
int i = 0;
String[] myStrings = new String[100];
while (scan.hasNextLine()) {
infix = scan.nextLine();
if (infix.length() > 0) {
myStrings[i] = infix;
i++;
} else {
break;
}
}
edit: wrong means , when I debug it, before I give strings as an input (after giving numbers) , this line :(" while (scan.hasNextLine()) ") passes , and infix in this line( infix = scan.nextLine(); is "") so the while , doesn't work correct. and break after that.
The issue is that after reading a float from the scanner, a newline "\n" is left in the scanner, this means that when the first scan.nextLine() runs, it gets that leftover newline, which results in your code hitting the else block, and breaking out of the loop.
You can either get the next line before your loop:
String infix;
int i = 0;
String[] myStrings = new String[100];
infix = scan.nextLine(); //Get it here to throw away the new line
while (scan.hasNextLine()) {
infix = scan.nextLine(); //Should contain whatever the user entered
//code
}
Or, when you get the float from the loop, you can use Float.parseFloat() combined with scan.nextLine(), like so:
for (int i = 97; i < 123; i++) {
alphabet[i] = Float.parseFloat(scan.nextLine());
}
Which will stop there from being a new line left in the scanner after you receive the last float
That's a common issue in Java. After getting the input from user using Scanner like nextInt();, nextDouble(); etc, you need to consume a line with a empty scan.nextLine();, because those methods doesn't consume the new line expression "\n". , before you can get some strings.