I'm working on creating a basic guitar inventory and I'm doing testing with scanner, I was trying to scan a blank entry and when there is a blank entry it should print "ANY" and it does, i'm using scan.useDelimiter("\z"); and now when I enter a correct entry like "fender" it should print "FENDER" but it just prints "ANY" as if the entry was incorrect.. someone know what I can do to solve that problem? Here is an sscce:
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
if (entry_1.equalsIgnoreCase("FENDER")
|| entry_1.equalsIgnoreCase("MARTIN")
|| entry_1.equalsIgnoreCase("GIBSON")
|| entry_1.equalsIgnoreCase("COLLINGS")
|| entry_1.equalsIgnoreCase("OLSON")
|| entry_1.equalsIgnoreCase("RYAN")
|| entry_1.equalsIgnoreCase("PRS"))
{
entry_1 = entry_1.toUpperCase();
System.out.println(entry_1);
}
else
{
entry_1 = "ANY";
System.out.println(entry_1);
}
}
}
By default, the scanner removes the delimiter from the tokens it return. When the delimiter was a line break (the default), when you do fender, entry_1 was assigned "fender". After you changed the delimiter, the line break caused by the enter is no longer removed, so you get "fender\n" in entry_1, causing your if condition to fail.
To fix, just do String entry_1 = scan.next().trim(); instead which removes the trailing linebreak.
You can try printing the scanned value to see why it is not going into the if statement.
import java.util.Scanner;
public class SSCCE {
public static void main(String[] args)
{
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z"); // count a blank entry (end of input)
String entry_1 = scan.next();
System.out.println("Input = [" + entry_1 + "]");
// rest of the code...
}
I think this is due to your use of \\z. Look at this regex tutorial for a more detailed story. For solving your problem, suffice it to say that changing it to \\Z should do the trick. The following code is working for me:
public static final Set<String> names = Sets.newHashSet("martin", "gibson", ...);
public static void main(String[] args) {
System.out.println("Enter a builder name: ");
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\Z"); // count a blank entry (end of input)
String entry = scan.next();
entry = "any" if (!names.contains(entry.toLowerCase());
System.out.println(entry.toUpperCase());
}
Note: I assumed you are scanning one name at a time. If not, then just use line break.
Related
Infinite loop using System.in and scanner.hasNext()
While taking input from user and storing it in a list newcomer(like me) generally thinks of using Scanner class for input and check for next input from user with hasNext() method as below. But often forgets the program will keep asking the user to provide input never endingly. What happens is as each time user press enter the hasNext() method thinks another input is generated and loop continues (Keep in mind pressing enter multiple times wont make a difference).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
List<String> wordsList = new ArrayList<String>();
while (scanner.hasNextLine())
wordsList.add(scanner.nextLine()); // Keeps asking user for inputs (never ending loop)
scanner.close();
for (String word : wordsList)
System.out.println(word);
}
}
Que. What are the working alternatives for above process which let user dynamically decide number of inputs without mentioning the total inputs anywhere.
Since you require that the user can enter any valid String as input, then you can:
Option 1:
The user can enter the number of entries they are going to give, before they give them. So then you only need to loop for the requested number of times. For example:
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of entries: ");
String[] wordsArray = new String[scanner.nextInt()];
scanner.nextLine(); //Skip the end of the line which contains the user's number of entries.
for (int i = 0; i < wordsArray.length; ++i) {
System.out.print("Entry " + (i + 1) + ": ");
wordsArray[i] = scanner.nextLine();
}
for (String word : wordsArray)
System.out.println(word);
}
}
Option 2:
If even the user does not know from the beggining how many entries they want, then you can ask them after every entry, like so:
import java.util.ArrayList;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
ArrayList<String> wordsList = new ArrayList<>();
do {
System.out.print("Entry " + (wordsList.size() + 1) + ": ");
wordsList.add(scanner.nextLine());
System.out.print("Enter an empty/blank line to insert another word, or anything else to stop and exit: ");
}
while (scanner.nextLine().trim().equals(""));
for (String word : wordsList)
System.out.println(word);
}
}
I know that this (the second) option may be a bit boring for the user to enter every time if they want to quit or not, but the only thing they have to do in order to quit the program (from the second option) is to type anything which will produce a non empty/blank line. They can simply hit a single ENTER key to continue giving entries.
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
I am trying to make a java program that given a string, I return the length of it, but I do not know why it does not catch me all. I'm starting with the programing. I've got here.
import java.util.Scanner;
public class lengt {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String cad = in.next();
System.out.println (cad);
System.out.println ("The length is:" + cad.length ());
}
}
There is a problem in your solution. in.next(); just take the first word of the chain, the one that is most immediate. If instead of using that you put it in.nextLine(); It takes you all the line you enter. You also have to be careful with length, which goes from 0 to n-1, when it comes to taking the length, since you could take one more and unnecessary. The solution for the problem that you pose would be, and there may be more, but one valid
import java.util.Scanner;
public class Example {
public static void main (String [] args) {
Scanner in= new Scanner (System.in);
String cad = in.nextLine();
System.out.println (cad);
System.out.println ("The length is:" + cad.length() - 1); //you can remove -1
}
}
So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()
I wanted to take a String using Scanner.next() and see if it contains a number or not. I used regex to check if a string contains anything but a number. The regex works correctly if the string is hard coded, but not when taken from keyboard. I expected input of 5 to be detected as a number, but it is not. Please tell me why. My code:
import java.util.Scanner;
public class Error {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int num = 0;
String input = "";
boolean isStringNumber = true;
System.out.println("\nPlease enter a number only...");
input = inp.nextLine();
isStringNumber = input.contains("[^0-9]+");
if (isStringNumber == false) {
System.out.println("\nYou entered a non number " + input);
}
}
}
contains uses a String literal as its argument. Use matches instead
isStringNumber = input.matches("[0-9]+");
or simply
isStringNumber = input.matches("\\d+");
BTW: Scanner has a nextInt method for accepting integer values
instead isStringNumber = input.contains("[^0-9]+");
try isStringNumber = input.matches("[0-9]+");