I'm trying to convert a String into a List. I'm getting the string by user input, but whenever I run my code, and it gives me this:
Enter a number: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
This is my code
public class ch3_15 {
public static void main(String[] args) {
int compNum, user_hund, user_ten, user_one, comp_hund, comp_ten, comp_one;
String s;
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.toString();
//generating random number
compNum = (int) Math.random() * 1000;
System.out.println(s);
//finding the hundreds, tens, and ones place of the user number
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
}
}
This is not error. It is expected behavior since you used
Scanner input1 = new Scanner(System.in);
s = input1.toString();
...
System.out.println(s);
and toString() returns String representing of object on which this method was invoked (in this case instance of Scanner).
If you want to use that Scanner to read line from user you should write
s = input1.nextLine();
// ^^^^^^^^
Your problem is that you don't read the next String from the console, but rather convert the Scanner to a String, which you then print.
What you want to use is Scanner.nextLine(), instead of toString().
Also, this is not a runtime error, but simply a wrong output.
you should use scanner.nextLine() to read next line that use enters.
Your current code is printing the toString() method of the scanner object and that is not a runtime error and is an expected behaviour.
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
You are not advancing from your current line; the method to use in this case is nextLine() from the class Scanner; So the code would be something like:
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
String aux = s.toString(); // To return the string representation from the sc
nextLine() method from Java API 7 => This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.**/
Related
I'm making a java program that has to store data using classes and objects, My question is how do input characters like a name ( billy ) into my code.
Here is the class i did.
class bank
{
int AccountID;
int HolderName;
double AccountBalance;
}
And i'm assigning here
angel.AccountID = 7532;
angel.HolderName = 753; // angel
angel.AccountBalance = angelbalance;
I know that i can input integers using the following code
System.out.println("Set Balance for Angel: ");
int angelbalance = sc.nextInt();
My question is how do i input text/characters in a way (scanner) does with integer
Sorry for the bad explanation.
Do you mean getting the name input using the Scanner object? Because you've imported java.util.Scanner, you can do:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
This will read the next line.
You can use (JOptionPane.showInputDialog) and it is easy to use if you want input from user
String name= JOptionPane.showInputDialog("Enter your name: "));
You need to either call the Scanner.nextLine() method or the Scanner.next() method to store String input such as a name like "Billy". Here is an example below:
//You can use the Scanner.next() method or the Scanner.nextLine() method to store Strings
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String billy = scan.next();
System.out.println("You entered: " + billy);
And here is your output:
Enter a name:
Billy
You entered: Billy
I'd check out the Scanner documentation here: https://docs.oracle.com/javase/8/docs/api/java/util/class-use/Scanner.html
I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
I have heard that nextInt() reads only the integers and ignores the \n at the end.
So why does the following code runs successfully?
Why there is no error after we enter value of a since \n must remain in the buffer ,
so use of nextInt() at b should give an error but it doesn't . Why?
import java.util.Scanner;
public class useofScanner {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int a = scanner.nextInt();
int b=scanner.nextInt();
System.out.println(a+b);
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
As another example, this code allows long types to be assigned from entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}
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.");
}
}