I am trying to read some data for a "Question" type, which has an id(int), statement(string) and answer(string). I'am using the code below:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
int id = scanner.nextInt();
System.out.print("Statement : ");
String statement = scanner.next();
System.out.print("Answer: ");
String answer = scanner.next();
If I enter sth like this "Who are you?" for "statement", it doesn't wait to type anything else for "answer" too. But if I do not use spaces in my statement it will work just fine. Also, if I use scanner.nextLine(), instead of scanner.next(), it doesn't work properly; it will allow me to introduce only one string for both statement and answer.
Does anyone have any idea?
try add scanner.nextLine(). It happens because scanner.nextInt() read only that number and not whole line, so rest of that line is still there. And you want to get rid of it so use nextLine() to get on next line.
It may look like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (unic!): ");
int id = scanner.nextInt();
//Consume rest of the line
scanner.nextLine();
System.out.print("Enunt : ");
String stat = scanner.next();
System.out.print("Raspuns: ");
String ras = scanner.next();
Change to :
String statement = scanner.nextLine();
String answer = scanner.nextLine();
instead of using scanner.next();
Basically when you want trying to input string with spaces then try to use scanner.nextLine() instead of using scanner.next()
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Here scanner.next() takes token without space. You may try scanner.nextLine()
The reason your code was not working is :that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
So you have to implement a nextLine() twice to get your output. As showed below.
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
int id = scanner.nextInt();
System.out.print("Statement : ");
scanner.nextLine();
String statement = scanner.nextLine();
System.out.print("Answer: ");
String answer = scanner.nextLine();
or You can Scan a dummy String variable before scanning the original String Variable as shown below:
Scanner scanner = new Scanner(System.in);
System.out.print("Id (uniquely!): ");
String k = ""; //Dummy String Variable
int id = scanner.nextInt();
System.out.print("Statement : ");
k = scanner.nextLine(); // scanning of Dummy variable
String statement = scanner.nextLine();
System.out.print("Answer: ");
String answer = scanner.nextLine();
Related
I'm reading words in a Scanner, but i need to know if the Scanner changes to the following line. this is for a Progress Bar(counting Lines).
Can you help me? Here is my code:
Pattern pattern = Pattern.compile("[^\\p{Alpha}]+");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNext()) {
sc.useDelimiter(pattern);
long totalLines = countLines(f);//Method that count Lines
System.out.println("Reading " + totalLines + "Lines...");
word = sc.next();//here i need to know if the scanner jumps to next Line or not.
Use hasNextLine() and nextLine() methods available in Scanner class.
iterate over lines.For each line,split that using space and count number of words in that.
I need to read lines of text from a file that i have prompted from the user. My java program is supposed to read the first line of this file and check to see if the last word of that line appears anywhere in the second line. without using repetition, arrays, or class construction I have come up with this so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter filename: ");
File userFile = new File(keyboard.nextLine());
keyboard.close();
Scanner input = new Scanner(userFile);
String firstLine = input.nextLine();
String secondLine = input.nextLine();
After here I have tried a lot of String methods but nothing is giving me back a satisfying result. I know I will need to finish my program with an if and else statement about whether or not the second line contains the last word in the first line.
**Having trouble finding a way to compare substrings (words within a line of text) that I do not actually know the location of or what the chars are. This is due to the fact that all the input is user generated. Is there even a way to compare substrings while retaining the actual chars and not converting to ints??
**UPDATE I AM ECSTATIC this is how I have solved this frustrating problem:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter filename: ");
File userFile = new File(keyboard.nextLine());
keyboard.close();
Scanner input = new Scanner(userFile);
String firstLine = input.nextLine();
String secondLine = input.nextLine();
int lastWordIndex;
lastWordIndex = ((firstLine.lastIndexOf(" ")) + 1);
String lastWord = firstLine.substring(lastWordIndex);
if (secondLine.contains(lastWord))
System.out.println("It is true the word " + lastWord
+ " appears in the text: " + secondLine);
else
System.out.println("The word: " + lastWord
+ " does not appear in the text: " + secondLine);
There are several methods to do this, but you need to get the last word in the firstLine string, then compare it with the secondLine string.
You can use the substring() method on your line, then use the lastIndexOf() method with the argument " " (i.e. whitespace). If you add one to this you will have the index of the first letter of the last word in your string.
This is how I would do it:
String lastWord = firstLine.replaceAll(".*\\s+", "");
boolean secondLineHasLastWord = secondLine.contains(lastWord);
or, to in-line it:
if (secondLine.contains(firstLine.replaceAll(".*\\s+", ""))) {
// yes
} else {
// no
}
Extracting the last word is done using a regex that matches everything up to and including the last whitespace character and replaces the match with nothing (effectively deleting it).
I'm reading from System.in, and I'm using the Scanner class. My problem is when I use redirection the last line in the file is not being read. I read the documentation for Scanner.readLine, and I'm guessing it's because it does not have a "end of line" character. Any idea what I can use instead to get this last line?
In my code input is "".
Scanner scanner = new Scanner(System.in);
int sizeOfList = scanner.nextInt();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
String input = scanner.nextLine();
System.out.println(input);
String[] splitInput = input.split(" |\\n");
for(int i = 0; i < splitInput.length; i++)
{
System.out.println(splitInput[i]);
arrayList.add(new Integer(Integer.parseInt(splitInput[i])));
}
instead of scanner.nextLine(), you could use scanner.next() .... This will get a string from the scanner when it does not have an end of line character.
You can also call scanner.hasNextLine() to check if you have reached the line at the end that you are worried about!
Here is how far I've done.
try
{
Scanner keyb = new Scanner(System.in);
System.out.print("Enter the name of the input file-> ");
String inFileName = keyb.next();
System.out.print("Enter the name of the output file-> ");
String outFileName = keyb.next();
ArrayList<Time> roster = new ArrayList<Time>();
Scanner fileIn = new Scanner(new File(inFileName));
while (fileIn.hasNext())
{
int hours = fileIn.nextInt();
int minutes = fileIn.nextInt();
String meridian = fileIn.next();
roster.add(new Time(hours,minutes,meridian));
}
fileIn.close();
Basically, what I have to do is read 'appointment.txt' file that has all different time that is in 11:30 a.m. form to sort it in order and save it different file name. But because of colon(:) in between hour and minutes, my while loop can't read time correctly and make error. What would make my while loop working?
Your while-loop is not correctly working because you check for fileIn.hasNext(), but afterwards use fileIn.nextInt() and fileIn.next() in different ways.
What you probably want to use is:
while (fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] bigParts = line.split(" ");
String[] timeParts = bigParts[0].split(":");
roster.add(new Time(
Integer.parseInt(timeParts[0]),
Integer.parseInt(timeParts[1]),
bigParts[1]
));
}
This reads the file line by line, then takes the line it has read. Following it splits the text up in three parts, first by (blank), then by : (colon).
UPDATE: Added Integer.parseInt() as it was originally done aswell.
/* txt file
Rolling Stone#Jann Wenner#Bi-Weekly#Boston#9000
Rolling Stone#Jann Wenner#Bi-Weekly#Philadelphia#8000
Rolling Stone#Jann Wenner#Bi-Weekly#London#10000
The Economist#John Micklethwait#Weekly#New York#42000
The Economist#John Micklethwait#Weekly#Washington#29000
Nature#Philip Campbell#Weekly#Pittsburg#4000
Nature#Philip Campbell#Weekly#Berlin#6000
*/
public class Zines {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("txt.file"));
input.useDelimiter("#|\n|\r|\r\n");
while(input.hasNext()) {
String title = input.next();
String author = input.next();
String publisher = input.next();
String city = input.next();
String line = input.nextLine();
//int dist = Integer.valueOf(line);
System.out.println(line);
}
}
}
Output is:
"#9000
"#8000
"#10000
"#42000
"#29000
"#4000
"#6000
Output 2:
9000
Rolling Stone
("Exception in thread "main") Jann Wenner
Weekly
Washington
4000
Nature
The question here is why does the #'s still appear after using the delimiter?
Because you are using Scanner#nextLine() to read the last part. It wouldn't consider the delimiter. It will read the complete remaining text after the previously read token, and not the next token.
So, if the previous token read is Boston, the remaining text - #9000, will be read by nextLine().
You should use scanner#next() instead.
String line = input.next();