How to extract elements from ArrayList specifically? - java

I am tasked to develop a program that prompts users to create their own questions and answers, which will be stored into the arrayList. After that, whenever the user types the same question, the program will automatically extract the answer.
What I did so far: I manage to store the questions and answers into the arrayList, but I have no idea how to trigger the program to extract exact answer when the user asked the question that he had just created. Here are my codes :
import java.util.ArrayList;
import java.util.Scanner;
public class CreateQns {
public static void main(String[] args) {
String reply;
ArrayList qns = new ArrayList();
ArrayList ans = new ArrayList();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner (System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if(!reply.equals("0")) {
qns.add(reply);
System.out.println("Enter your answer ==>");
System.out.print("You: ");
ans.add(input.nextLine());
}
else {
System.out.println("<==End==>");
}
}while(!reply.equals("0"));
}
}

You may use a HashMap<String, String> which stores Key/value
The user enter a question, check if it is in the map, if yes print the answer, if not ask the answer and store it :
public static void main(String[] args) {
String reply;
HashMap<String, String> map = new HashMap<>();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner(System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if (!reply.equals("0")){
if (map.containsKey(reply)) // if question has already been stored
System.out.println(map.get(reply)); // print the answer
else {
System.out.println("Enter your answer ==>");
System.out.print("You: ");
map.put(reply, input.nextLine()); // add pair question/answer
}
}else{
System.out.println("<==End==>");
}
} while (!reply.equals("0"));
}
But to answers directly to what you ask, instead of the map.contains() you should do :
int index;
if ((index = qns.indexOf(reply)) >= 0){
System.out.println(ans.get(index));
}
But that is less convenient, less powerfull than Map

Please find the code without using the HashMap.
import java.util.ArrayList;
import java.util.Scanner;
public class CreateQns {
public static void main(String[] args) {
String reply;
ArrayList<String> qns = new ArrayList();
ArrayList<String> ans = new ArrayList();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner (System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if(!reply.equals("0")) {
if(qns.contains(reply))
{
System.out.println("your answer is==>"+ans.get(qns.indexOf(reply)));
}
else
{
qns.add(reply);
System.out.println("Enter your answer ==>");
System.out.print("You: ");
ans.add(input.nextLine());
}
}
else {
System.out.println("<==End==>");
}
}while(!reply.equals("0"));
}
}

You need to use a Map<String, String> to correlate the question you are asking to the response the user typed in for it.
Your code should say: if the questions map contains the question the user just typed in, then print the value associated to the question in the map, otherwise ask the user to type and answer and add the question/answer to the map.

Related

Java Array List - finding duplicate in While loop

I tried solving this ArrayList problem but no luck
Anyway in while loop I have to add new String items to the ArrayList.
If there is a duplicate item there should be a message that says REPEATED ITEM.
While loop will break by word END
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
lista1.add(in.nextLine());
if(lista1.containsAll(lista1)){
System.out.println("Repeated words");
}
if(lista1.contains("end")) {
break;
}
}
for(String data:lista1)
System.out.println(data);
}
If I understand what you're trying to do correctly, I believe it appears that you're trying to loop over user input until they type "end", each input to a list, and state if you already added that word by printing out "repeated word". If that's the case, you're pretty close. You just need to understand how to use the list data structure a little bit better.
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
String userInput = in.nextLine();
if (lista1.contains(userInput)) { // checks if user's input is already in lista1
System.out.println("Repeated word: " + userInput);
} else { // if it's not, then add user's input to lista1
lista1.add(userInput);
}
if (lista1.contains("end")) { // if lista1 contains "end", exit loop
break;
}
}
for(String data:lista1)
System.out.println(data);
}

Getting multiple Strings into an Array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm having difficulties with my homework. I have the basic logic down but I'm messing up. The objective is to make a receipt from a shopping list that's inputted by the user. For example, the user enters:
Apples
OraNgeS // also it's not case sensitive
Oranges
Bananas
!checkout //this is to indicate the list is over
Output:
Apples x1
Oranges x2
Bananas x1
I'm stuck. My code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Enter the items you wish to buy:");
String[] input = new String [keyboard.nextLine()];
keyboard.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = keyboard.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
I know I'll have to add the if statement eventually so if they type in "!checkout" it'll end the list. but I can't get past this yet.
Any tips or advice?
Try to use ArrayList <-- Link.
Array is need to statically initialize it first before you can use it while ArrayList is automatically expanding when you add values on it. you can use ArrayList without initializing a range on it. Here is the sample:
List<String> fruitList = new ArrayList<>();
Scanner keyboard = null;
Boolean isNotDone = true;
System.out.println("Press 'Q' if you want to print out.");
while(isNotDone) {
keyboard = new Scanner(System.in);
System.out.print("Input Fruits: ");
String temp = keyboard.nextLine();
if(temp.equalsIgnoreCase("q")) {
isNotDone = false;
} else {
fruitList.add(temp);
}
}
System.out.println(fruitList);
The following code will do exactly what you are looking for:
Scanner keyboard = new Scanner(System.in);
List<String> inputItems = new ArrayList<String>();
List<String> printedResults = new ArrayList<String>();
String input = keyboard.nextLine();
while(!"!checkout".equals(input))
{
inputItems.add(input);
input = keyboard.nextLine();
}
for(int i=0; i<inputItems.size();i++)
{
Integer thisItemCount = 0;
String currentItem = inputItems.get(i);
for(int j=0; j<inputItems.size();j++)
{
if(inputItems.get(j).toLowerCase().equals(currentItem.toLowerCase()))
thisItemCount++;
}
if(!printedResults.contains(currentItem.toLowerCase()))
{
System.out.println(currentItem.toLowerCase() + " x" + thisItemCount);
printedResults.add(currentItem.toLowerCase());
}
}

Reading many strings input in Java with scanner

I have a project that involves me to create a program that reads the user input and the program then tells them what zone they are in, but I cant seem to how to add multiple strings.
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
// I would like more stations to be added but I don't no how
if ("Mile End".equals(answer)) {
System.out.println( input +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again");
}
}
}
It seems like you want a loop. One such option, would be to stop when the user enters a special "zone" (like quit below).
String answer = input.nextLine();
while (!answer.equalsIgnoreCase("quit")) {
// I would like more stations to be added but I don't no how
if ("Mile End".equals(answer)) {
System.out.println( input +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again. "
+ "Quit to stop.");
}
answer = input.nextLine();
}
am not entirely sure what you mean by "but I cant seem to how to add multiple strings." but you seem to print the Scanner object " System.out.println( input +" is in Zone 2");" instead of the answer
System.out.println( answer +" is in Zone 2");
Could it be because of this you are not seeing the expected result ?
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
if (answer.equals("Mile End")) { // i would like more stations to be added but i dont no how
System.out.println( answer +" is in Zone 2");
} else {
System.out.println("That is not a Station, please try again");
}
}
You may need an else if statement
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
if ("Mile End".equals(answer)) {
System.out.println( answer+" is in Zone 2");
} else if("Hobbitland".equals(answer) {
System.out.println( answer +" is in Zone 42");
} else
System.out.println("That is not a Station, please try again");
}
}
}
Alternatively you could use a switch like:
import java.util.*;
public class hello {
public static void main (String args[]){
Scanner input = new Scanner (System.in);
String answer = input.nextLine();
switch(answer){
case "Mile End":
System.out.println( answer +" is in Zone 2");
break;
case "Hobbitland":
System.out.println( answer +" is in Zone 42");
break;
default:
System.out.println("That is not a Station, please try again");
break;
}
}
}
There are still other means to solve this problem without the need of such a complex control structure. Just create a Map that holds your station names as key and their zone as value. When you get an input you just look it up in your map and retrieve its zone. If it's not in your map you print your error message.
Why not create a map where the zone is the key and the value is a list of stations that come under that zone?
You can then have a method that handles the population of the map...
private static Map<String, List<String>> createZoneMap() {
Map<String, List<String>> zoneMap = new HashMap<String, List<String>>();
// Probably want to populate this map from a file
return zoneMap;
}
Then your main can look something like...
public static void main(String args[]) {
Map<String, List<String>> zoneMap = createZoneMap();
Scanner scan = new Scanner(System.in);
String input;
while (true) {
input = scan.nextLine();
// Some code to exit the application...
if (input.equalsIgnoreCase("quit")) {
System.out.println("Exiting...");
System.exit(1);
}
String zone = findZone(zoneMap, input);
if (zone != null) {
System.out.println(input + " is in " + zone);
} else {
System.out.println("That is not a Station, please try again");
}
}
}
Then when you type in the station name you look through the map to find the zone which the station comes under, if its not present then return null or something
private static String findZone(Map<String, List<String>> zoneMap, String station) {
// Maybe make this more versatile so that it does not care about case...
for (Map.Entry<String, List<String>> entry : zoneMap.entrySet()) {
if (entry.getValue().contains(station)) {
return entry.getKey();
}
}
return null;
}
Hope that's a good starting point for you. You could also consider moving away from performing all of your logic in the main method and instead create an instance of your class in the main.

How to take input for 'char' array in Java?

I am developing a small application to grade Multiple Choice Questions submitted by the user. Each question has obviously 4 choices. A,B,C,D. Since these answers will be stored in a two dimensional array, I want to ask how can I take input from user for char variable. I have not learnt any method to take input for char arrays on console. i.e I have just worked with nextInt(), nextDouble(), nextLine() etc. These methods are for Strings and Integers not for char. How to take input for char arrays? I am going to post code snippet of taking input so that you people can better understand.
public class MCQChecker{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
char[][] students=new char[8][10];
for (int i=0;i<8;i++)
{
System.out.println("Please enter the answer of "+students[i+1]);
for(int j=0;j<10;j++)
{
students[i][j]=?;//Im stuck here
}
}
}
}
Once you get the .next() value as a String, check if its .length() == 1, then use yourString.charAt(0).
students[i][j]=input.next().charAt(0);
What you need is more than char to handle your requirement. Create a question class which will have question and correct answer, user entered answer.
public static class Question {
private Choice correctChoice = Choice.NONE;
private Choice userChoice = Choice.NONE;
private String question = "";
public Question(String questionString, Choice choice) {
this.question = questionString;
this.correctChoice = choice;
}
public void setUserChoice(String str) {
userChoice = Choice.valueOf(str);
}
public boolean isQuestionAnswered() {
return correctChoice == userChoice;
}
public String question() {
return question;
}
}
enum Choice {
A, B, C, D, NONE
}
Now you can create a List of questions and for each question you can check whether it was answered correctly or not.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Question> questions = new ArrayList<Question>();
questions.add(new Question("question1", Choice.A));
questions.add(new Question("question2", Choice.A));
questions.add(new Question("question3", Choice.A));
for (Question q : questions) {
System.out.println("Please enter the answer of " + q.question());
String str = input.next();
q.setUserChoice(str);
System.out.println("You have answered question "
+ (q.isQuestionAnswered() == true ? "Correctly"
: "Incorrectly"));
}
}
Above program now allows you to ask questions and reply to user accordingly.
When question is asked if choice entered other than correct answer then question will be marked incorrectly.
In above example if other character is entered than A then it will tell user that you are incorrect.
You can't take input directly in charArray as because there is no nextChar() in Java.
You first have to take input in String then fetch character one by one.
import java.util.*;
class CharArray{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
char ch[]=new char[11];
String s = scan.nextLine();
for(int i=0;i<=10;i++)
ch[i]=s.charAt(i); //Input in CharArray
System.out.println("Output of CharArray: ");
for(int i=0;i<=10;i++)
System.out.print(ch[i]); //Output of CharArray
}
}

I have applied a check for not allowing alphabets.But its not working

import java.util.Scanner;
public class Main extends Hashmap{
public static void main(String[] args) {
Hashmap hm = new Hashmap();
int x=0;
Scanner input = new Scanner(System.in);
do{
System.out.print("Enter any integer value between 1 to 12: ");
x = input.nextInt();
}while(x<=0 || x>12);
Scanner sc = new Scanner(System.in);
//int number;
do {
while (!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next();
}
x = sc.nextInt();
}while(x>=0);
String month = hm.getEntry(x);
System.out.println(month);
}
}
here I need to restrict user from entering an alphabet.But its not working.
pls help...
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
/**
* Populate hashmap.. Your logic goes here
*/
Scanner sc = new Scanner(System.in);
int x;
System.out.println("Enter a number between 1 and 12");
do {
while (!sc.hasNextInt()) {
System.out.println("That's not a number! Enter a number between 1 and 12");
sc.next();
}
x = sc.nextInt();
String month = hm.get(x);
System.out.println("The corresponding month is " + month);
} while (x >= 0);
}
I think this is what you are trying to achieve..
First, have a look at polygenelubricants comprehensive answer to your problem again. I'm pretty sure, he solved it for you in Example 3.
Then, as an alternative design for a user interface: accept any user input, validate the input and if the input is not correct, provide a helpful message and ask the user to enter a value again. This is much, much easier to implement and a user should be happy with this too.

Categories

Resources