I have this task where I have to handle some user input. The user should only be able to enter a,b,c,d,e,f,g,h,i,j,k,l and after the user input I want to assign a,b,c..l to variables 0,1,2,3,4..,11. Every other input, except for capital letters should give an error - but how can I do this?
I got as far as this:
int number;
public String playerInput;
public void start()
{
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " +playerInput);
}
I really don't know how I would be able to just store mentioned letters and assign them to variables, can someone help?
Since it unclear what you meant by Assiging it to variable from number.
so here i'm giving you idea how to just input char between a-l and then you can do the things with you input
public class CharInput {
public static void main(String... str) throws IOException {
// open Scanner for input
Scanner keyboard = new Scanner(System.in);
System.out.println("Input");
//since you want only lowercase as input so converting at front is an better option
String playerInput = keyboard.next().toLowerCase();
// to make sure we have only char input nothing else
char input = playerInput.charAt(0);
// Check if the inputted char is between a and l only
if (input >= 'a' && input <='l' ){
// Do the stuff you want to do if the input is in between
// with the char variable input
}
else{
System.out.println("Error Raised");
}
}
}
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Prog {
int[] array = new int[12];
Set<String> list = new HashSet<String>();
String alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,A,B,C,D,E,F,G,H,I,J,K,L";
int count = 0 ;
public String playerInput;
public void start() throws Exception
{
String[] val = alphabet.split(",");
while(count<24){
list.add(val[count]);
count++;
}
Scanner scn = new Scanner( System.in );
while(count < 12){
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " + playerInput);
if(list.contains(playerInput)){
//assign your desired value to that letter
}
else{
//throw exception here ;
}
}
}
}
I didnt understand your problem clearly but i guess may be you want to do something like this(not sure though) -
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
int i=0;
Map<String,Integer> map=new TreeMap<String,Integer>();
Set<String> set= new TreeSet<String>();
while(playerInput.matches("[a-lA-L]")){
set.add(playerInput.toLowerCase());
playerInput=scn.nextLine();
if(!playerInput.matches("[a-lA-L]")){
System.out.println("Error!!! Wrong Input");
break;
}
}
for(String s:set){
map.put(s, i);
i++;
}
System.out.println(map);
Related
I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}
I am having problem in taking a hole paragraph as input in java using System.in and storing it in an array. but problem is with while loop is not ending and program stuck in the loop. i have tried many methods but loop is not ending.
Scanner sc = new Scanner(System.in);
ArrayList < String > al = new ArrayList<>();
System.out.print("Please Enter Paragraph + \n");
while (!(sc.equals(null))) {
al.add(sc.next());
}
Scanner sc = new Scanner(System.in);
String para = sc.nextLine();
int x = 0;
while (para != null) {
if (sc.hasNextLine()) {
ParaArray[x] = para;
para = sc.nextLine();
x++;
} else {
para = null;
}
}
sc is a Scanner object. When you compare sc with null, you will never get true because sc could never be null. Also, your code seems to have a lot of errors. Your question is also unclear. Please provide a proper question...
-Thanks
Tejan Gandhi
Dt: 29th July (After reading your comment):
There are 2 parts of code, one which scans characters and another scans lines.. Because the first "while" loop compares sc (which is a Scanner object) it can never be null and loop can never end.. So instead of doing
sc.equals(null)
sc.hasNext()
Tell me if that works for you.
when you use "sc.hasNextline",you should put"Scanner sc= new Scanner(System.in); " before your judgment statement,just like this:
int num = 0;
while (true) {
System.out.println("Please input a number");
Scanner sc = new Scanner(System.in);
if (sc.hasNextDouble()) {
num = sc.nextDouble();
} else {
System.out.println("It is not a number,please try again!");
System.out.println("============================");
}
}
After your first loop you have already an array of paragraphs so why it is not clear why you need a second loop.
I've also put the scanner in a try () because Scanner is Closeable so it is closed at the end.
import java.util.ArrayList;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
ArrayList<String> al = new ArrayList<>();
while (true) {
System.out.println("Please Enter Paragraph + \n");
String readLine = sc.nextLine();
if (readLine.length() == 0) {
break;
}
al.add(readLine);
}
System.out.println("result:"+al);
}
}
}
Below is the code that I wrote in order to have a user input a few different strings, check if each is a palindrome, and only return the palindrome. Currently, all of the entered in strings will be returned. It seems that the IF statement if not working correctly. Any suggestions on how to have the correct strings returned?
import java.util.Scanner;
public class hh {
static void checkPalin () {
// creates a scanner
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
// asks the user for the number of strings
System.out.print("Enter the number of strings: ");
StringBuilder sentence = new StringBuilder(userInput);
StringBuilder palindrome = new StringBuilder();
// stores the number of strings user will enters
int stringNumber = input.nextInt();
// prompts the user to enter in their sentences
System.out.println("Enter the strings:");
// this loop will go until the number of strings entered are entered
while(i <= stringNumber){
userInput = input.nextLine();
if(sentence.reverse().equals(sentence)){
palindrome.insert(0, " " + userInput);
}
i ++;
}
// if( sentence == sentence.reverse()){
System.out.println("The palindromes are: " + palindrome);
}
public static void main(String[] args) {
checkPalin();
}
}
You need to create the String from the StringBuilder using the toString method before calling equals:
if(new StringBuilder(userInput).reverse().toString().equals(userInput)) { ... }
When you declare
StringBuilder sentence = new StringBuilder(userInput);
The "sentence" variable will not change if userInput changes. You need to recreate the StringBuilder each time you need it.
Here is the fixed code :
static void checkPalin() {
Scanner input = new Scanner(System.in);
int i = 0;
String userInput = "";
System.out.print("Enter the number of strings: ");
StringBuilder palindrome = new StringBuilder();
int stringNumber = input.nextInt();
System.out.println("Enter the strings:");
while (i <= stringNumber) {
userInput = input.nextLine();
String reversed = new StringBuilder(userInput).reverse().toString();
if (reversed.equals(userInput)) {
palindrome.insert(0, " " + userInput);
}
i++;
}
System.out.println("The palindromes are: " + palindrome);
}
You have to write something like
new StringBuilder(sentence.toString()).reverse().equals(sentence)
in your if
I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.
thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}