How to take input for 'char' array in Java? - 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
}
}

Related

Why I input a string with space but can not print out it fully? [duplicate]

This question already has answers here:
Scanner doesn't see after space
(7 answers)
Closed 1 year ago.
I am writing a very simple program to input a string with space and then output it, my problem is, it not printed out fully as I expected.
Here is my code, as you can see, very simple
import java.util.Scanner;
public class Testjapanese {
public static void main(String[] args) {
String x;
Scanner keyboard = new Scanner(System.in);
System.out.println(" Add a string");
x = keyboard.next();
System.out.println(x);
}
}
For example, it print "Add a string" but when I input a string "Today is very", it gave me "Today", not "Today is very".
I search and they said to me that I should use input.nextLine(), but I do not know how to use it.
May be I must use public java.lang.String nextLine() first ?
Sorry if my question is easy to solve. Thank you for your answer.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
String x;
Scanner keyboard = new Scanner(System.in);
System.out.println(" Add a string");
x = keyboard.nextLine();
System.out.println(x);
}
}
You should just replace next with nextLine as below
public static void main(String[] args) {
String x;
Scanner keyboard = new Scanner(System.in);
System.out.println(" Add a string");
x = keyboard.nextLine();
System.out.println(x);
}

How to extract elements from ArrayList specifically?

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.

Knapsack Solution using Recursion and Array

I would like to know the best possible way to modify this code. Instead of adding the integers to an array in the code itself, I would like the user to input the different weights and the capacity via keyboard.
Now I am currently having compiling errors when inserting the data. I believe the problem lies within the for loop.
import java.util.*;
public class NN01276494 {
public static ArrayList <Double> sack = new ArrayList <Double> ();
public static void main(String [] args){
Scanner in = new Scanner (System.in);
int i =0;
for(i = 0; i<sack.length; i++){
System.out.println("Enter Capacity");
sack.size(in.nextDouble());
}
while (in.hasNextDouble()){
System.out.print("Enter weights");
sack.add(in.nextDouble());
i++;
}
}
public static Boolean knapsackproblem(double targetWeight, int index)
{
Boolean complete = false;
if(index == sack.size()) return false;
if(sack.get(index) == targetWeight)
{
System.out.print("Answer: " + sack.get(index) + " ");
complete = true;
}; //DONE
if(sack.get(index) < targetWeight)
{
complete = knapsackproblem(targetWeight-sack.get(index), index+1);
if(complete) System.out.print(sack.get(index) + " ");
for(int i = index+1; i < sack.size(); i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i);
}
}
if(sack.get(index) > targetWeight) complete =
knapsackproblem(targetWeight, index+1);
return complete;
}
}
The most common way to accept user input in java is the Scanner class. This allows your users to input into the console, and your program to use their input. Here is the javadoc that details scanners in detail, but here's all you need to do to accept integer inputs from your users:
First, import the scanner dictionary so you can use it.
import java.util.Scanner;
This will give you access to the Scanner library. To construct the scanner, you need to specify an input stream in the declaration. To make the console this input stream, declare it like so:
Scanner nameOfScanner = new Scanner(System.in);
Now, to get the integers for the array, use the method .nextInt() as many times as you want. Make sure to ask the user separately for each input, and if you want the user to be able to control the size of the array, you can also ask the user for that. Just in case you don't know, you can declare an array to have a certain size, but not specify what is going to be in each location until later like so:
int[] nameOfArray = new int[sizeOfArray];
On a separate note, I noticed that you had a semicolon after the closing bracket of your if statement in the middle of the knapsackproblem() method. I don't know if that's a typo in your question or actually in your code, but it really shouldn't be there.
I hope this helps, and good luck coding!
I've modified your code so user can input the array via an ArrayList :-using ArrayList user can input data without regard to length just enter as many values as you want then at the end type any letter for ex:[Out] then your method should start working :).
import java.util.*;
public class knapsack {
public static void main(String [] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter Capacity");
int y = in.nextInt();
double [] sack = new double [y];
System.out.println("enter values");
for (int i =0;i<y;i++){
sack[i]=in.nextDouble();
}
}
public static Boolean knapsackproblem(double targetWeight, int index ,
double [] sack)
{
Boolean complete = false;
if(index == sack.length) return false;
if(sack[index] == targetWeight)
{
System.out.print("Answer: " + sack[index] + " ");
complete = true;
}; //DONE
if(sack[index] < targetWeight)
{
complete = knapsackproblem(targetWeight-sack[index], index+1,sack);
//keep going
if(complete) System.out.print(sack[index] + " ");
for(int i = index+1; i < sack.length; i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i,sack);
}
}
if(sack[index] > targetWeight) complete = knapsackproblem(targetWeight,
index+1,sack);
return complete;
}
}
Hope it helps.Also I've fixed your recursion since you wrote knapsack( instead of knapsackproblem(.ArrayList comes from java,util package which also includes the Scanner class I just got them all using * ArrayList is a class that has its own methods like .size() and .add().

Issue with user input and .equals() in Java

I'm fairly new to java coding but the error is that if I type in the correct answer or the incorrect answer, it still says both Correct and Incorrect.
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals(20));
System.out.println("Correct!");
if (!"20".equals(question));
System.out.println("Incorrect!");
}
}
Remove the semi-colons from the end of your if statements. It's treated as an empty line.
Or even use explicit curly braces, like if(foo) { bar(); }.
Your conditional if's are a little wrong, this should do it: (untested)
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20"))
System.out.println("Correct!");
if (!"20".equals(question))
System.out.println("Incorrect!");
}
}
In your original code, you had ; at the end of the if's. Which informs the compiler that it's the end of the line. Hence why both "Correct!" and "Incorrect!" were being displayed. AS they weren't part of the conditional statement.
Hope this helps! :)
Find your solutions Brother.......
Tip: for String use "20" instead of 20
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")){
System.out.println("Correct!");
}else{
System.out.println("Incorrect!");
}
}
}
Semicolon ends the if statement, so the statements below each if will always execute. In addition this: if (question.equals(20)) should be if (question.equals("20")) as the user input is String and you want to compare Strings.
The code should read as follows:
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")) {
System.out.println("Correct!");
}
if (!"20".equals(question)) {
System.out.println("Incorrect!");
}
}
}
It is worth mentioning that the Scanner has other methods to read user input, e.g. you can read Integer instead of String like this: Integer answer = answer = user_input.nextInt(); And then you just compare Integers like:
if (answer == 20) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
That is because you have a semicolon after the if. Remove it, and preferably put curly braces around the println statements to show which statements belong to the if. Right now, you have written
if (...); a;
Which is equivalent to
if (...)
{
}
a;
While what you meant is
if (...)
{
a;
}
Make it simple
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
System.out.println(user_input.next().equals("20") ? "Correct" : "Incorrect");

Java: Using scanner to read in boolean values failing.

import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}

Categories

Resources