In this program, I am supposed to return how many questions I got right and wrong. But regardless of what I put down, it'll say that I got 20 questions correct, and 0 wrong. Anyone know how to fix this so it'll be more accurate than that?
Class:
public class KNW_DriverExam
{
//Create the arrays/Declare variable
//Intialize theAnswers array
private String[] theAnswers = {"B" , "D" , "A" , "A" , "C" ,
"A" , "B" , "A" , "C" , "D" ,
"B" , "C" , "D" , "A" , "D" ,
"C" , "C" , "B" , "D" , "A" };
private String[] userAnswers;
int[] missed = new int [theAnswers.length];
/**The DriverExam method, recieves answers
* #param Answer, the answer
* */
public KNW_DriverExam(String[] Answer)
{
userAnswers = new String[theAnswers.length];
for(int i = 0; i < theAnswers.length; i++)
{
userAnswers[i] = theAnswers[i];
}
}
/**The passed method, see if user passes or fails
* #return true if user passed
* #return false if user failed
* */
public boolean passed()
{
if(totalCorrect()>=15)
{
return true;
}
else
{
return false;
}
}
/**The totalCorrect method, see how many user got right
* #return correctCount, how many the user got right
* */
public int totalCorrect()
{
int correctCount = 0;
for(int i = 0; i < theAnswers.length; i++)
{
if(userAnswers[i].equalsIgnoreCase(theAnswers[i]))
{
correctCount++;
}
}
return correctCount;
}
/**The totalIncorrect method, how many the user got wrong
* #return incorrectCount, how many the user got wrong
* */
public int totalIncorrect()
{
int incorrectCount = 0;
for(int i = 0; i < theAnswers.length; i++)
{
if(!(userAnswers[i].equalsIgnoreCase(theAnswers[i])))
{
missed[incorrectCount] = i;
incorrectCount++;
}
}
return incorrectCount;
}
/**The missedQuestions method, how many quetions user missed.
* #return missed, missed questions
* */
public int[] questionsMissed()
{
return missed;
}
}
Demo:
import java.util.Scanner;
public class KNW_DriverExamDemo
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Driver's Exam/n");
System.out.println("20 Multiple Choice Questions Mark A,B,C,D");
//Inputting string
String[] answers = new String[20];
String answer;
for(int i = 0; i < 20; i++)
{
do
{
System.out.println((i + 1) + ": ");
answer = input.nextLine();
}
while(!isValidAnswer(answer));
{
answers[i] = answer;
}
}
KNW_DriverExam exam = new KNW_DriverExam(answers);
System.out.println("Results\n\n");
System.out.println("Total Correct: " + exam.totalCorrect() + "\n");
System.out.println("Total Incorrect: " + exam.totalIncorrect() + "\n");
if(exam.totalIncorrect() > 0)
{
System.out.println("The Incorrect Answers Are: ");
int missedIndex;
for(int i = 0; i < exam.totalIncorrect(); i++)
{
missedIndex = exam.questionsMissed()[i] + 1;
System.out.println(" " + missedIndex);
}
}
}
public static boolean isValidAnswer(String answer)
{
return "A".equalsIgnoreCase(answer) ||
"B".equalsIgnoreCase(answer) ||
"C".equalsIgnoreCase(answer) ||
"D".equalsIgnoreCase(answer);
}
}
Take a look at your constructor. When you're assigning to userAnswers you're using theAnswers and not the supplied Answer.
public KNW_DriverExam(String[] Answer) {
userAnswers = new String[Answers.length];
for(int i = 0; i < Answers.length; i++) {
userAnswers[i] = Answers[i];
}
}
Related
I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}
I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sim;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static jdk.nashorn.internal.objects.NativeMath.max;
/**
*
* #author admin
*/
public class Sim {
public String[][] bigramizedWords = new String[500][100];
public String[] words = new String[500];
public File file1 = new File("file1.txt");
public File file2 = new File("file2.txt");
public int tracker = 0;
public double matches = 0;
public double denominator = 0; //This will hold the sum of the bigrams of the 2 words
public double res;
public double results;
public Scanner a;
public PrintWriter pw1;
public Sim(){
intialize();
// bigramize();
results = max(res);
System.out.println("\n\nThe Bigram Similarity value between " + words[0] + " and " + words[1] + " is " + res + ".");
pw1.close();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Sim si=new Sim();
// TODO code application logic here
}
public void intialize() {
int j[]=new int[35];
try {
File file1=new File("input.txt");
File file2=new File("out.txt");
Scanner a = new Scanner(file1);
PrintWriter pw1= new PrintWriter(file2);
int i=0,count = 0;
while (a.hasNext()) {
java.lang.String gram = a.next();
if(gram.startsWith("question")|| gram.endsWith("?"))
{
count=0;
count-=1;
}
if(gram.startsWith("[")||gram.startsWith("answer")||gram.endsWith(" ") )
{
//pw1.println(count);
j[i++]=count;
count=0;
//pw1.println(gram);
//System.out.println(count);
}
else
{
// System.out.println(count);
count+=1;
//System.out.println(count + " " + gram);
}
int line=gram.length();
int sa_length;
//int[] j = null;
int refans_length=j[1];
//System.out.println(refans_length);
for(int k=2;k<=35;k++)
// System.out.println(j[k]);
//System.out.println(refans_length);
for(int m=2;m<=33;m++)
{
sa_length=j[2];
//System.out.println(sa_length);
for(int s=0;s<=refans_length;s++)
{
for(int l=0;l<=sa_length;l++)
{
for (int x = 0; x <= line - 2; x++) {
int tracker = 0;
bigramizedWords[tracker][x] = gram.substring(x, x + 2);
System.out.println(gram.substring(x, x + 2) + "");
//bigramize();
}
// bigramize();
}
}
}
bigramize();
words[tracker] = gram;
tracker++;
}
//pw1.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Sim.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void bigramize() {
//for(int p=0;p<=sa_length;p++)
denominator = (words[0].length() - 1) + (words[1].length() - 1);
for (int k = 0; k < bigramizedWords[0].length; k++) {
if (bigramizedWords[0][k] != null) {
for (int i = 0; i < bigramizedWords[1].length; i++) {
if (bigramizedWords[1][i] != null) {
if (bigramizedWords[0][k].equals(bigramizedWords[1][i])) {
matches++;
}
}
}
}
}
matches *= 2;
res = matches / denominator;
}
}
I have tried the above code for bigramizing the words in the file "input.txt" i have got the result of bigram but i didnt get the similarity value.
for e.g:
input file contains as
answer:
high
risk
simulate
behaviour
solution
set
rules
[2]
rules
outline
high
source
knowledge
[1]
set
rules
simulate
behaviour
in the above example I have to compare the words under answer with every word under [2] as {high,rules} {high,outline} {high,high} {high,source} {high,knowledge} and I have to store the maximum value of the above comparison and again the second word from answer is taken and then similar process is taken. At last, mean of maximum value of each iteration is taken.
I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner in java programming. I am trying to recreate a simplified version of the card game war. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at cardgame.BuildDeck(cardgame.java:36)
at cardgame.main(cardgame.java:60)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
-FGxMatta
public class cardgame
{
static class TheCard
{
// Java getter & setter
private String CardName;
private int CardRank;
private int Chosen;
public TheCard(int rank, String name)
{
this.CardName = name;
this.CardRank = rank;
this.Chosen = 0;
}
}
#SuppressWarnings("null")
private static TheCard[] BuildDeck()
{
TheCard[] TheDeck = null;
String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
int[] Rank = {2,3,4,5,6,7,8,9,10,11,12,13,14};
int cardnumber = 0;
for (int i = 0; i < Cards.length; i++)
{
for (int j = 0; j < Suits.length; j++)
{
String deckcard = Cards[i];
String suitcard = Suits[j];
String cardname = deckcard + "-" + suitcard;
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
cardnumber++;
}
}
return TheDeck;
}
private static TheCard GetRandomCard(TheCard[] OrderedDeck)
{
TheCard thecard;
int random = (int) (51*Math.random ());
thecard = OrderedDeck[random];
if (thecard.Chosen == 0 ) // if available...
{
thecard.Chosen = 1; // mark it taken...
return thecard;
}
else
{
return GetRandomCard(OrderedDeck);
}
}
public static void main(String args[])
{
TheCard[] OrderedDeck = BuildDeck();
System.out.println ("Welcome, Prepare for War!");
int decksize = OrderedDeck.length;
int player1wincount = 0;
int player2wincount = 0;
int tiecount = 0;
for (int cardcount = 0; cardcount < decksize;)
{
TheCard Player1 = GetRandomCard(OrderedDeck);
cardcount++;
TheCard Player2 = GetRandomCard(OrderedDeck);
cardcount++;
System.out.println ("Player 1's card is: " + Player1.CardName);
System.out.println ("Player 2's card is: " + Player2.CardName);
if (Player1.CardRank > Player2.CardRank)
{
System.out.println("Player 1 wins this hand");
player1wincount++;
}
if (Player1.CardRank < Player2.CardRank)
{
System.out.println("Player 2 wins this hand");
player2wincount++;
}
if (Player1.CardRank == Player2.CardRank)
{
System.out.println("Player 1 and Player 2 played the same valued card");
tiecount++;
}
}
System.out.println ("Player 1 won " + String.valueOf(player1wincount) + " hands");
System.out.println ("Player 1 won " + String.valueOf(player2wincount) + " hands");
System.out.println ("There were " + String.valueOf(tiecount) + " ties");
}
}
Replace:
TheCard[] theDeck = null;
with:
TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
and move it to below the declarations for Cards and Suits.
Null Pointer Exception is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’. A simple example can be:
package au.com.copl;
public class Demo{
public static void main(String[] args) {
String d = null;
System.out.println(d.toString()); // d is un-initialized and is null
}
}
right here
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
you never initialized TheDeck. You probably want something like
TheDeck = new TheCard[52];
before you start putting things in the array.
as a note, java convention is that variable names be camel cased. So "CardName" should be cardName. Just a convention.
TheCard[] theDeck = null; ?
dont you need to inialize it?
You should also use new in main method:
TheCard[] OrderedDeck = BuildDeck();
should be replaced by:
TheCard[] OrderedDeck = new BuildDeck();