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};
Related
package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.
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.**/
I am trying to figure out how to accumulate user inputs in for loop and then to print them out with one system.out.print. This is my test code for the problem.
So for example if a user type : Mike for his name and Joe,Jack,Dave for other names, how to print them all just having one variable because amount of variables are not known since a user has that decision. Also is it possible to do that without stringbuilder and without arrays?
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
String othernames = " ",name;
int count,n;
Scanner kybrd = new Scanner(System.in);
System.out.println("Enter your name ");
name = kybrd.nextLine();
System.out.println("How many other names would you like to add ? ");
count = kybrd.nextInt();
kybrd.nextLine();
for(n=0;n<count;++n){
System.out.println("Enter other names ");
othernames = kybrd.nextLine();
}
System.out.println("Other names are "+othernames + " And your name is "+ name);
}
}
You can call it recursively, for instance:
Scanner sc = new Scanner(System.in);
String s;
while(condition) {
s = s + sc.nextLine();
}
this will always concat the lines you enter, you can also add commas, or spaces, or whatever you want to add.
as for your question about using Objects other than StringBuilder you can use List<String> and build a string for it at the final step.
you can use Map<String, String> if you need more complex data structure.
I have a scanner that reads the input but it needs to quit when it reads 'q'.
The problem is that I can't find a way to do this.
Scanner sc = new Scanner(System.in);
System.out.println("question 1");
str1 = sc.nextLine();
System.out.println("question 2");
str2 = sc.nextLine();
System.out.println("question 3");
str3 = sc.nextLine();
The questions represents user information...
This is just an example code but it demonstrates my problem as soon as the user press q it must quit. Any ideas?
Thanks in advance!
Usually it's done like this
String input = "";
ArrayList<String> list = new ArrayList<String>();
while (!(input = scan.nextLine()).equals("q")) {
// store the input (example - you can store however you want)
list.add(input);
}
but in your case, you could also incorporate a list of questions that you can cycle through.
ArrayList<String> questions = new ArrayList<String>();
questions.add("q1");
questions.add("q2");
questions.add("q3");
Scanner scan = new Scanner(System.in);
String input = "";
ArrayList<String> userInput = new ArrayList<String>();
int index = 0;
// print the first question and increment the index
System.out.println(questions.get(index));
index++;
while (!(input = scan.nextLine()).equals("q")) {
// store the input (example - you can store however you want)
userInput.add(input);
// print the next question since the user didn't enter q
// if there are no questions left, stop asking
if (index == questions.size() - 1) {
break;
}
System.out.println(questions.get(index));
// keep track of the index!!
index++;
}
scan.close();
At the end of the question asking, you can use the values in the list of userInputs. Answers are stored starting from index 0, and correspond to the matching question list.
On a side note, if you actually wanted to detect when the user pressed "q" before he pressed enter, you could implement a KeyListener on the q button... (however, this would stop the program every time the user's valid input started with a q) see http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html for more detail
The person before me is correct, but you might also try
String input = ""
ArrayList<String> list = new ArrayList<String>();
while (true){
input = sc.nextLine();
if (input.equals("q"))
break;
list.add(input)
}
is more readable and your intentions for stopping the code are far more clear.
Hope this helps.
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
char[] course; //course code format: ABCDE##
String code;
//int num;
System.out.println("Input Course: ");
course = keyboard.next();
System.out.println(course);
code = String.copyValueOf(course, 0, 4);
System.out.println(code);
}
}
I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?
The instruction is the user will input a course code in the format: ABCDE##
Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.
Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...
Why not just read a string directly with scanner.nextLine?
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input Course: ");
String course = keyboard.nextLine();
System.out.println(course);
String code = course.substring(0, 5); //You put 4 but it left out the last letter in the course name. I changed it to 5 and it worked but I'm confused since the index always start with 0.
System.out.println(code);
String num = course.substring(5, 6);
System.out.println(num);
}
}