I'm a beginner in Java, so I apologize if this seems too easy for you to reply, still I hope I can get a little help from here.
I wanted to get an input from the user with Scanner, writing a sentence.
Then the user would pick a word from that sentence.
And then with string.indexof(""), the program should count from which number the word starts in that sentence.
But the result is always -1. And I don't understand why.
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
y=sc.next();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.next())));
But the result is always -1. And I don't understand why.
The only scenario in which -1 will be returned is if there is no such occurrence of the specified String.
Scanner#next() only returns what comes before a space, meaning anything after space is ignored. It seems that you'll need to use the Scanner#nextLine to store the whole sentence rather than Scanner#next().
e.g.
y = sc.nextLine();
{
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
String y=sc.nextLine();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.nextLine())));
}
Related
for some reason I am having an issue where the scanner keeps getting no input and doesn't wait for the user to actually input anything, leading to an infinite loop. This is what my code looks like:
Scanner kb = new Scanner(System.in); //Takes user input
System.out.println("Please enter your name");
String input = "";
if(kb.hasNextLine())
{
input = kb.nextLine();
}
while(input.isEmpty())
{
System.out.println("Please try again: ");
if(kb.hasNextLine())
input = kb.nextLine();
}
System.out.println(input);
I know issues can occur if I was using kb.next() instead of nextLine because of the buffer, but this doesn't seem to be the case. I'm pretty confused and think this should be simple enough but unfortunately it's not. All it does for me is print "Please try again:" over and over without waiting for my input. Any help would be appreciated.
I am having trouble with a user-entered number. I am trying to add the user-entered number a few spaces after the colon in the sentence instead of the line underneath.
Scanner inputHere = new Scanner(system.in);
System.out.println("I am trying to add the number a few spaces after the colon:");
String inputHereOne = inputHere.nextLine();
Change
System.out.println("I am trying to add the number a few spaces after the colon:");
to not print a newline - you should also flush() when you do so. Like,
System.out.print("I am trying to add the number a few spaces after the colon: ");
System.out.flush();
Also, you had a typo here
new Scanner(system.in);
should be
new Scanner(System.in);
Change the lowercase 's' in 'system.in' to 'System.in'
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
Im having some trouble with scanning user input in one of my first java programs. When I compile and run this, I am immediately prompted for input (i.e the command line stops and blinks). When I enter anything, the first line is printed, asking me to enter an integer. Then the second line is printed and I'm prompted to enter another value.
The output from this program is the first two values that I input. This is hard to explain, but it basically asks for 3 input values and only uses two.
import java.util.Scanner;
public class objects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer please...");
int input = sc.nextInt();
System.out.println("Enter your name please...");
String name = sc.nextLine();
System.out.println("The read values: " + input + ", " + name);
sc.close();
}
}
Put a System.out.flush() command after your println statements if you're reading from the console directly afterward
just use this:
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name please... ");
String name = sc.nextLine();
System.out.print ("Enter an integer please... ");
int input = sc.nextInt();
System.out.println ("The read values: " + input + ", " + name);
i just moved the integer below the name and it sorta fixed it. hahaha
When you introduce a number you press enter key, nextInt() uses the number but the enter (\n) remains buffered. After this if you call again nextInt(), Java tries to convert \n into a number giving you a NumberFormatException, but if you invoke nextLine() they read the enter as empty string
Here you have a better explanation and one solution
Can't use Scanner.nextInt() and Scanner.nextLine() together
It seems this is an error to do with my installation of VirtualBox. No matter what I try, the problem persists. Even if i try to only read ONE integer, it will ask me to input two values.
Thanks for everyone who tried to help, I learned a lot just trying to debug this.
I have following code and am facing a problem if I use System.in.read() before Scanner.
Then the cursor moves at the end by skipping nextLine() function.
import java.util.Scanner;
public class InvoiceTest{
public static void main(String [] args) throws java.io.IOException {
System.out.println("Enter a Charater: ");
char c = (char) System.in.read();
Scanner input = new Scanner(System.in);
System.out.println("Enter id No...");
String id_no = input.nextLine();
System.out.println("Charater You entered "+ c +" Id No Entered "+ id_no);
}
}
You are not consuming the newline character upon entering your character(System.in.read()) thus the input.nextLine() will consume it and skip it.
solution:
consume the new line character first before reading the input of for the id.
System.out.println("Enter a Charater: ");
char c = (char) System.in.read();
Scanner input = new Scanner(System.in);
System.out.println("Enter id No...");
input.nextLine(); //will consume the new line character spit by System.in.read()
String id_no = input.nextLine();
System.out.println("Charater You entered "+c+" Id No Entered "+id_no);
}
EJP comments thus:
Don't mix System.in.read() with new Scanner(System.in). Use one or the other.
Good advice!
So why is it a bad idea to mix reading from the stream and using Scanner?
Well, because Scanner operations will typically read ahead on the input stream, keeping unconsumed characters in an internal buffer. So if you do a Scanner operation followed by a call to read() on the stream, there is a good chance that the read() will (in effect) skip over characters. The behaviour is likely to be confusing and unpredictable ... and dependent on where the input characters are actually coming from.
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}