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.
Related
I am incredibly new to java and have been given the following task:
Write a Java Program to prompt a user for a 3 letter body part name which has to be in the 'official' list of 3 letter body parts. (Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe)
If a user makes a guess correctly then display the correct guess as part of a list.
Allow the user to keep guessing until they have all 10.
If a body part is incorrect then display an appropriate message.
Display the number of guesses they have made including
the correct ones.
The advice given was to use Arrays and Collections as well as Exception Handling where appropriate but I don't know where to go from what I've coded so far. Any help would be appreciated so much, thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] bodyparts = new String [10];
bodyparts[0] = "Arm";
bodyparts[1] = "Ear";
bodyparts[2] = "Eye";
bodyparts[3] = "Gum";
bodyparts[4] = "Hip";
bodyparts[5] = "Jaw";
bodyparts[6] = "Leg";
bodyparts[7] = "Lip";
bodyparts[8] = "Rib";
bodyparts[9] = "Toe";
Set<String> bodypartSet = new TreeSet<>();
Collections.addAll(bodypartSet, bodyparts);
System.out.println("Please enter a 3 letter body part: ");
String bodypart = input.nextLine();
if (bodypartSet.contains(bodypart)) {
System.out.println("Correct, " + bodypart + " is on the list!");
} else {
System.out.println("Nope, try again!");
}
}
There are a lot of way to do this. The following, isn't the best or the most efficient, but it should work...
First of all, you have to put your "official" list in a structure, like an array:
private static String[] offList={Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe};
Now you have to write a method that can find a world in that "offList", like that:
private static boolean find(String word){
for( int i=0; i<offList.length; i++){
if(word.equals(offList[i])) //if "word" is in offList
return true;
}
return false;
}
Now, let's create this guessing game GUI:
public static void main(String[] args){
LinkedList<String> guessed=new LinkedList<>();
String s;
Scanner input = new Scanner(System.in);
while(guessed.size()<offList.length){
System.out.println("Guessed= "+guessed.toString()); //you have to change it, if you want a better look
System.out.print("Try:");
s=input.nextLine();
/*Here we ask to the user the same thing, unless the guessed list
contains all the words of offList.
Every time we print the guessed worlds list*/
if(find(s)){
System.out.println("This world is in offList!");
if(!guessed.contains(s)) //the world is counted only one time!
guessed.add(s);
}else
System.out.println("Sorry...");
}
System.out.println("The complete list is "+guessed.toString());
}
If you want to show this game in a window, you should have to study some Java Swing classes.
EDIT: I post my answer before the main post editing. First of all you have to understand the Collections advantages and usage... When you know all the LinkedList methods, for example, this assignment looks like a joke! ;)
You need a loop for that, otherwise it will only ask for input once.
Something like this should do:
ArrayList<String> bodyParts = new ArrayList<String>();
bodyParts.add("Arm");
bodyParts.add("Ear");
bodyParts.add("Eye");
bodyParts.add("Gum");
bodyParts.add("Hip");
bodyParts.add("Jaw");
bodyParts.add("Leg");
bodyParts.add("Lip");
bodyParts.add("Rib");
bodyParts.add("Toe");
String input = "";
int totalGuesses = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Start guessing...");
while (!bodyParts.isEmpty()) {
totalGuesses++;
input = sc.nextLine();
if (input.length() != 3 || !bodyParts.contains(input)) {
// incorrect, do nothing
System.out.println("Nope.");
} else {
// correct, remove entry
bodyParts.remove(input);
System.out.println("Correct! " + (10 - bodyParts.size()) + " correct guess" + ((10 - bodyParts.size()) != 1 ? "es" : ""));
}
}
System.out.println("Done. You have found them all after " + totalGuesses + " guesses.");
sc.close();
Also, this is case sensitive. It will not find Arm when typing arm. And if you need the number of all guesses you can simply add an int before the loop and increase it inside.
The result of my example:
Start guessing...
arm
Nope.
Arm
Correct! 1 correct guess
Arm
Nope.
Ear
Correct! 2 correct guesses
Eye
Correct! 3 correct guesses
(...)
Rib
Correct! 9 correct guesses
Toe
Correct! 10 correct guesses
Done. You have found them all after 12 guesses.
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};
Im looking for a form to make Scanner to stop reading when you push the first time (so, if I press the key K automatically the program considerer that I press the Intro key, so it stop to recognise inputs, save the K and keep going with the program).
Im using char key= sc.next().charAt(0); in a beginning, but dont know how to make it stop without pushing Intro
Thanks in advance!
If you want to stop accepting after a single particular character you should read the user's input character by character. Try scanning based on a Pattern of one single character or using the Console class.
Scanner scanner = new Scanner(System.in);
Pattern oneChar = new Pattern(".{1}");
// make sure DOTALL is true so you capture the Enter key
String input = scanner.next(oneChar);
StringBuilder allChars = new StringBuilder();
// while input is not the Enter key {
if (input.equals("K")) {
// break out of here
} else {
// add the char to allChars and wait for the next char
}
input = scanner.next(oneChar);
}
// the Enter key or "K" was pressed - process 'allChars'
Unfortunately, Java doesn't support non blocking console and hence, you can't read user's input character by character (read this SO answer for more details).
However, what you can do is, you can ask the user to enter the whole line and process each character of it until Intro is encountered, below is an example:
System.out.println("Enter the input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringBuilder processedChars = new StringBuilder();
for(int i=0 ; i<input.length() ; i++){
char c = input.charAt(i);
if(c == 'K' || c == 'k'){
break;
}else{
processedChars.append(c);
}
}
System.out.println(processedChars.toString());
I recently picked up Java and I am having an issue with some console input.
Basically, I want to read in an array of ints from the console in a format like this :
1 2 3 4 5 6
I looked through some examples on the forums and decided to do this by using the scanner nextInt() method.
My code currently looks like this :
Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();
while (get.hasNextInt()) {
elements.add(get.nextInt());
}
The problem with this code is that the while loop doesn't stop when I hit "Enter" on the console.
Meaning that after I enter some numbers (1 3 5 7) and then hit enter, the program doesn't continue with execution, but instead waits for more integers. The only way it stops is if I enter a letter to the console.
I tried adding !get.hasNextLine() as a condition in my while loop, but this didn't help.
I would be very greatful, if anyone has an idea how can I fix this.
If you want to read only one line the simpliest answer may be the best :)
Scanner in = new Scanner(System.in);
String hString = in.nextLine();
String[] hArray = hString.split(" ");
Now, in array hArray you have all elements from input and you can call them like hArray[0]
You can read one line, and then use that to construct another Scanner. Something like,
if (get.hasNextLine()) {
String line = get.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextInt()) {
elements.add(lineScanner.nextInt());
}
}
The Scanner(String) constructor (per the Javadoc) constructs a new Scanner that produces values scanned from the specified string.
Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
myArr[i++]=Integer.parseInt(stTokens.nextToken());
}
java-8
You may use the following. User just has to enter each integer without pressing enter and press enter at the end.
Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
I'm still new to programming and have been trying to learn how to fix this code
im trying to input and record a username and password depending on how many users I input, but when i run it it prints out the "whats your username?" question twice before i'm allowed to give a response. I've narrowed the problem down to the user[i]=in.nextLine() part
public static void main(String[] args){
System.out.println("How many Users?");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
String[] user;
user = new String[x];
String[] pass;
pass = new String[x];
for(int i=0; i<x;i++){
System.out.println("What is your Username?");
user[i] = in.nextLine();
Add in.nextLine(); after int x = in.nextInt(); to consume and ignore the new line character left over by call to nextInt()
When you use a scanner it consume only the bytes needed for the requested token.
If the first call is to get the number of users (nextInt) it reads only the minimum number of digits composing it and leave the \n (new line character) not consuming it.
Because you are asking for the next line on the loop the first nextLine use only the \n.
So the best solution to make your code correct is to add a
in.nextLine();
before the for loop.