I'm new to java and I working on this project to answer questions from a text file in random order. NO MULTIPLE CHOICE In the end it has count how many questions you got wrong. In the code you have to make a class called QAndA, with "a" as anwser and "q" as question in the data fields. Then at the end of that class make a toString() method to return "a" and "q". I will show that below.
class QAndA{
String q; //question
String a; //answer
QAndA(String q, String a){
this.q = q;
this.a = a;
}
public String getQ(){
return q;
}
public String getA(){
Scanner input = new Scanner(System.in);
System.out.println("Enter your answer: ");
a = input.next();
return a;
}
#Override
public String toString(){
return q;
}
}
All there is to fix is just taking a question one at a time from the file and inputting the answer to see if its right. Also we have to use an ArrayList class with the QAndA objects. Example: ArrayList theNameoftheArray = new ArrayList();
Here is what the text file is suppose to look like:
Q: How do you call a general binary relationship that describes an activity between two classes?
A: association
Q: Defining multiple methods with the same name as long as their parameter lists are different is called?
A: overloading
Q: Write a statement that assigns the value true to the first element of the array butterfly.
A: butterfly[0] = true;
Q: When the return type of a method is an array, it actually returns?
A: a reference to the array
Q: True or false (T/F)? Constructors have the return type void.
A: F
Any help will be appreciated! Thank You!
Actually stackoverflow shouldn't be a place to ask for full solutions for programs - anyway as you are new here -> here is my mini solution (without appropriate error handling!)
package at.mad.max;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QandAMain {
static class QAndA {
String q; // question
String a; // answer
public QAndA(String q, String a) {
this.q = q;
this.a = a;
}
public String getQ() {
return q;
}
public String getA() {
return a;
}
}
public static String readAnswerFromConsole() {
System.out.println("Enter your answer: ");
return new Scanner(System.in).next();
}
public static List<String> readFileFromResourceLineByLine(String fileName) throws IOException, URISyntaxException {
URL resource = QandAMain.class.getClassLoader().getResource(fileName);
if (resource != null) {
return Files.readAllLines(new File(resource.toURI()).toPath(), StandardCharsets.UTF_8);
}
return Collections.emptyList();
}
public static void main(String[] args) throws IOException, URISyntaxException {
Pattern pattern = Pattern.compile("^Q: (.+[^A:]) A: (.+)");
List<String> lines = readFileFromResourceLineByLine("q_and_a.txt");
List<QAndA> qAndAs = new ArrayList<QandAMain.QAndA>();
lines.forEach(l -> {
Matcher m = pattern.matcher(l);
if (m.find()) {
qAndAs.add(new QAndA(m.group(1), m.group(2)));
}
});
Collections.shuffle(qAndAs);
for (int i = 0; i < qAndAs.size(); i++) {
QAndA qa = qAndAs.get(i);
System.out.println("-- Question ("+(i+1)+" of "+qAndAs.size()+"): --\n"+qa.getQ());
String userAnswer = readAnswerFromConsole();
if (userAnswer != null && qa.getA().trim().equalsIgnoreCase(userAnswer.trim())) {
System.out.println("Shiiish\n");
} else {
System.out.println("Nope\n");
}
}
System.out.println("Done!");
}
}
You need to place a file with the above mentioned questions and answers in the resource path - in my example I called the file "q_and_a.txt".
You get following output:
-- Question (1 of 5): --
True or false (T/F)? Constructors have the return type void.
Enter your answer:
F
Shiiish
-- Question (2 of 5): --
How do you call a general binary relationship that describes an activity between two classes?
Enter your answer:
association
Shiiish
-- Question (3 of 5): --
When the return type of a method is an array, it actually returns?
Enter your answer:
a pointer
Nope
...
...
Related
I have the following text file with either 0 or 1 in first then two strings all three are separated by commas:
0 , Bx , Cz
1 , By , Cx
0 , Bz , Cy
etc. , etc. , etc.
And I have the following code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
public class Manager {
static Scanner scanner;
public Manager() {
}
public static void chooseFile(String thisFile) {
try {
scanner = new Scanner(new File(thisDeck));
scanner.useDelimiter(",");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static String getB() {
String b = null;
if (scanner.hasNextLine()) {
String a = scanner.next();
do {
if (a.equals("1")) {
scanner.nextLine();
a = scanner.next();
}
if (a.equals("0")) {
b = scanner.next();
}
} while (scanner.hasNextLine() && a.equals("1"));
}
if (!scanner.hasNextLine()) {
b = “Done.”;
}
return b;
}
static String getC() {
String c = null;
if (scanner.hasNextLine()) {
c = scanner.nextLine().substring(2);
} else {
c = “Done.”;
}
return c;
}
static void changeA1() {
//Here I want to change a value in the first "column" A to 1
//The row/line to be changed is the one that the scanner just passed
}
static void changeA0() {
//Here I want to change a value in the first "column" A to 0
//The row/line to be changed is the one that the scanner just passed
}
}
My question is how can I change the value A to 0 or 1? The GUI (which calls this class) only allows the user to change the value-A after calling the getB() and then getC(), so the scanner is at the end of the line when the functions for changing the value A of a line will be called. Can I edit value-A with a second scanner or is there another way?
Scanner doesn't allow any modification of a file at all. You'll have to use a FileWriter or another class for this purpose. And it's in general not recommendable to use two objects to modify and read a file at the same time. Most classes don't even allow this, due to the fact that the file-content will usually be streamed (the file is open all the time and a new chunk is loaded when the complete buffer has been processed).
The simplest approach would most likely be a RandomAccessFile (http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html).
This can aswell speed up the complete code quite a lot, if the values are always fixed-size. But it's rather difficult to recommend anything without more information about the structure of the file.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class NNNTest {
private String SkillNeed="Java;C++;C";
private String SkillHave="SQL:8;Java:9;C++:5;C:9;PHP:5";
public boolean CheckAvailable(){
int flag=0;
int k;
String [] snar=SkillNeed.split(";");
String [] shandlevel=SkillHave.split(";");
for(int i=0;i<snar.length;i++){
for(k=0,flag=0;k<shandlevel.length;k++){
if(shandlevel[k].split(":")[0].equals(snar[i])){
System.out.println(shandlevel[k].split(":")[0]);
flag=1;
}
}
if(flag==0){
break;
}
}
if(flag==1){
System.out.println("YES");
return true;
}
else{
System.out.println("NO");
return false;
}
}
public static void main(String[] args) {
NNNTest n=new NNNTest();
n.CheckAvailable();
}
}
The method check if you have enough skills to acquire the job.
SkillNeed is a String that with form "skill;skill;skill....."
SkillHave is the skills and level you have and with form "skill:level;skill:level;...."
These are the codes that I typed,but I think it's pretty long and boring,do you have any other way to improve the method?Something like skipping the loop or Array or using java given methods.
Simply way with java-8:
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class NNNTest {
private static String skillNeed = "Java;C++;C"; //the skills the job need
private static String skillHave = "SQL:8;Java:9;C++:5;C:9;PHP:5"; //skill and level you have
public static boolean checkAvailable() { //if all the job needed skills match the skills you have
return Arrays.stream(skillHave.split(";")).map(s -> s.split(":")[0]).collect(Collectors.toSet()).containsAll(Arrays.asList(skillNeed.split(";")));
}
public static void main(String[] args) {
System.out.println(checkAvailable());
}
}
Edited for explanation:
Collect al skillHave in a Set (without the number).
Check if the Set of skillHave contains all elements of a given collection.
Collect all SkillNeed in another Set and pass it as parameter for previous step.
Another Java 8 Solution..
It basically iterates through all required skills and makes sure, using the allMatch() function, that each skill is contained in the givenSkills-String. Keep in mind, that you have to check for ":" aswell, otherwise "C" would also match "C++". This also makes sure, that it exactly matches the skill, since the skill is either at the beginning, or it is enclosed by ; and :.
public static boolean checkForRequiredSkills(String requiredSkills, String givenSkills)
{
return Arrays.stream(requiredSkills.split(";")).allMatch(skill -> givenSkills.startsWith(skill + ":") || givenSkills.contains(";" + skill + ":"));
}
A similar solution in earlier java versions could be looking like this
public boolean checkAvailable()
{
for (String skill : skillNeed.split(";"))
{
if (!skillNeed.startsWith(skill + ":") && !skillHave.contains(";" + skill + ":"))
return false;
}
return true;
}
Also the preferred idiom, to iterate over an Array or List is using a for-each loop..
for(String str : stringArray)
doSomething(str);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}
Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped
I've read a text from file into an array. I'd like to iterate through this array in another class (to reverse an array and find every 5th element). I have a problem with use this array in another class - this class cannot see array. Could anyone help me?
package iterators;
import java.util.*;
import java.io.*;
import iterators.*;
public class Dunno{
int i = 1;
String[] something() throws IOException {
BufferedReader read = new BufferedReader(new FileReader("file.txt"));
StringBuilder sb = new StringBuilder();
String text = read.readLine();
while (text != null) {
sb.append(text);
sb.append("\n");
text = read.readLine();
}
String all = sb.toString();
String film = all;
String znak = ",";
String[] tab;
tab = film.split(znak);
for (i = 0; i < tab.length; i++) {
System.out.println(tab[i]);
}
return tab;
}
}
And 2nd class:
public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}
In your second class you're calling the first class method in class scope, you're not calling it in a method or in main. Here is how you should do it:
public class Dunno1 {
public static void main(String[] args) throws IOException {
Dunno1 d1 = new Dunno1();
Dunno dunn = new Dunno();
String[] d = dunn.something();
d1.dunn(d);
}
public String dunn(String [] d) {
return null;
// Iterate
}
}
You need to construct an object of your second class as well so that you can call the dunn method and pass it the String array you're getting from your first class (That's why the signature of the method in my answer is different).
public class Dunno1{
Dunno dunn=new Dunno();
dunn.something();
public String dunn(){
//Iterate
}
}
The above doesn't compile, because you can't execute instructions directly inside classes. Classes must contain field declarations, constructors and methods. But not instructions.
The following would compile:
public class Dunno1{
public void foo() {
Dunno dunn = new Dunno();
String[] array = dunn.something();
// iterate over the array.
}
}
This is realy basic stuff that you should learn by reading a Java book, or a tutorial. Not by asking questions on StackOverflow.