I am creating a Combination Lock class in Netbeans and I am confused as to why when I run the file I do not recieve any output. Anyone know what I am doing wrong? Any and all help would be greatly appreciated! Here is the code in my constructer class :
package combinationlock ;
/**
* A class to implement a combination lock with 26 dial positions
* and a three-letter combination
*
* #Carlos
*/
public class CombinationLock
{
// instance variable declarations go here
private boolean open ;
private int Count ;
private String position1 ;
private String position2 ;
private String position3 ;
private String first = "F" ;
private String second = "I" ;
private String third = "U" ;
/**
* Creates a lock with a given combination consisting of three upper-case characters.
* #param first the first letter of the combination
* #param second the second letter of the combination
* #param third the third letter of the combination
*/
public CombinationLock(String first, String second, String third)
{
this.first = first ;
this.second = second ;
this.third = third ;
open = false ;
Count = 0 ;
}
/**
* Set the dial to a position
* #param aPosition a String consisting of a single uppercase letter (A..Z)
*/
public void setPosition(String aPosition)
{
if (Count == 0)
{
position1 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 1)
{
position2 = aPosition ;
Count = Count + 1 ;
}
else if (Count == 2)
{
position3 = aPosition ;
}
}
/**
* Try opening the lock
*/
public void tryToOpen()
{
if (first.equals(position1) && second.equals(position2) && third.equals(position3))
{
open = true ;
System.out.println("Its open!") ;
}
else
{
open = false ;
System.out.println("Wrong combination! Please try again.") ;
}
}
/**
* Check whether the lock is open
* #return true or false indicating whether the lock is open
*/
public boolean isOpen()
{
return open ;
}
/**
* Close the lock and print a message indicating that the lock is now closed
*/
public void lock()
{
Count = 0 ;
open = false ;
System.out.println("You re-apply the lock") ;
}
}
And here is the code I used in my tester class:
package combinationlock ;
import javax.swing.JOptionPane ;
/**
*
* #author Carlos
*/
public class CombinationLockTester
{
public static void main (String[] args)
{
CombinationLock MasterLock = new CombinationLock("A", "B", "C");
String input = JOptionPane.showInputDialog
("Please enter first letter.") ;
MasterLock.setPosition(input) ;
String input2 = JOptionPane.showInputDialog
("Please enter second letter.") ;
MasterLock.setPosition(input2) ;
String input3 = JOptionPane.showInputDialog
("Please enter third letter") ;
MasterLock.setPosition(input3);
System.out.println("The combination entered was " +input + input2 +input3) ;
}
}
You are setting positions on MasterLock but not calling the tryToOpen method. Try this and see if you get any output:
MasterLock.tryToOpen();
Which should be called after the three calls to setPosition.
Related
I am trying to create a calculator in Maven and I got stuck when I was trying to implement multiplication. When I changed the args array in launch.json to 2 * 6, it returned nothing.I also tried - "\\* but nothing happened. Also when I put the multiplication boolean to boolean mul = Arrays.stream(args).anyMatch("".equals);, It worked.
Here is my code -
import java.util.Arrays;
/**
* Hello world!
*/
public final class App {
/**
* #param args The arguments of the program.
*/
public static void main(String[] args) {
boolean plus = Arrays.stream(args).anyMatch("+"::equals);
boolean minus = Arrays.stream(args).anyMatch("-"::equals);
boolean div = Arrays.stream(args).anyMatch("/"::equals);
// here ->
boolean mul = Arrays.stream(args).anyMatch("*"::equals);
/**
Or should I put it like this ->
boolean mul = Arrays.stream(args).anyMatch("\\*"::equals);
*/
if (plus == true) {
String plus1 = args[0];
String plus2 = args[2];
int plus1_int = Integer.parseInt(plus1);
int plus2_int = Integer.parseInt(plus2);
System.out.println(plus1_int + plus2_int);
}else {
;
}
if (minus == true) {
String min1 = args[0];
String min2 = args[2];
int min1_int = Integer.parseInt(min1);
int min2_int = Integer.parseInt(min2);
System.out.println(min1_int - min2_int);
}else {
;
}
if (div == true) {
String div2 = args[2];
String div1 = args[0];
int div1_int = Integer.parseInt(div1);
int div2_int = Integer.parseInt(div2);
System.out.println(div1_int / div2_int);
}else {
;
}
// and here ->
if (mul == true) {
String mul1 = args[0];
String mul2 = args[2];
int mul1_int = Integer.parseInt(mul1);
int mul2_int = Integer.parseInt(mul2);
System.out.println(mul1_int * mul2_int);
}else {
;
}
}
}
Have I done something wrong?
Thanks in advance!
* when you use it on command line it refers to file or directory existing in the working directory. Therefore, your args instead of having 2, *, 6 it will be 2, file1, directory1, etc, 6.
The solution is to escape it by quote or double quote.
2 '*' 6
or
2 "*" 6
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];
}
}
The issue I am having is figuring out how to link my button class to my main program. I realize I have a lot of methods from external classes so I will try to give an overview. Basically I have an arrayList of quotes and a key created from a random permutation of the alphabet. I use this key to "encrypt" the quote. Via this method:
public static String translate ( String text, String key )
{
String newText = "";
for( int i = 0; i < text.length(); i++ )
{
char currentLetter = text.charAt( i );
if( ALPHA.contains( Character.toString( currentLetter ) ) )
{
int index = ALPHA.indexOf( currentLetter );
char newLetter = key.charAt( index );
newText = newText + text.substring( i, i + 1 ).replace
( currentLetter, newLetter ) ;
}
else
newText = newText + currentLetter;
}
return newText;
}
So what I want to do is to have a button that takes user input and replaces the letters in the quote with that input. I'm not using JButton, I'm using a library to make a square and then using mouseEvent. I made the button in a separate class here:
import wheelsunh.users.*;
import java.awt.Color;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
/**
* Creates a button
*
* #author Scott
*/
public class SubstituteButton extends RoundedRectangle
{
String response;
public SubstituteButton( int x, int y )
{
super( x, y );
super.setSize( 20, 20 );
super.setFillColor( Color.LIGHT_GRAY );
super.setFrameColor( Color.BLACK );
}
public void mousePressed( MouseEvent e )
{
super.setFillColor( new Color( 131,111,255 ) );
try
{
response = JOptionPane.showInputDialog( "Which letter"
+ " would you like to replace? Ex. ab would replace all a's"
+ " with b's" );
}
catch( NullPointerException exeception )
{
JOptionPane.showMessageDialog( null, "Input Error" );
}
super.setFillColor( Color.LIGHT_GRAY );
}
public String getInput()
{
if( response.length() == 2 &&
Character.isLetter( response.charAt( 0 ) ) &&
Character.isLetter( response.charAt( 1 ) ))
{
return response;
}
return null;
}
public static void main( String args[] )
{
new Frame();
new SubstituteButton( 100, 100 );
}
}
HSo how would I update the displayed quote so that it replaces the letters? I was thinking I could just use the replace() method in the button class, but it doesn't update the displayed quote. Here is the main program:
import wheelsunh.users.*;
import java.util.*;
import java.lang.Character;
/**
* Displays a quote with letters in blocks and punctuation without blocks.
* If a letter has been changed from the original then it is highlighted.
* Displayed lines must be broken to stay on frame.
*
*
* #author Scott
*/
public class CryptogramApp extends ShapeGroup
{
private ArrayList< String > blockQuote;
private int quoteLength;
private SubstituteButton substituebutton;
private boolean newState = true;
private String key, quote, encryptedQuote;
/**
* Creates a block-quote with first letter at initialX,initialY
* with the text from quote.
*
* #param initialX int
* #param initialY int
* #param quote String
*/
//--------------------------------------------------------------------------
public CryptogramApp( int initialX, int initialY )
{
if( newState == true )
newQuote();
int newx = initialX;
for( int i = 0; i < quote.length(); i++ )
{
String letter = Character.toString( encryptedQuote.charAt( i ) );
BlockLetter b = new BlockLetter( newx, initialY, letter );
newx += BlockLetter.WIDTH;
if( letter.equals(" ") && b.getXLocation() > 400 )
{
newx = initialX;
initialY += 40;
}
}
newState = false;
}
public void newQuote()
{
blockQuote = new ArrayList<String>();
key = StringUtilities.getRandomKey();
quote = getRandomQuote();
System.out.println( key );
encryptedQuote = StringUtilities.translate( quote, key );
System.out.println( encryptedQuote );
substituebutton = new SubstituteButton( 425, 350 );
}
//--------------------------------------------------------------------------
/**
* Returns the String text with the jth character replaced with key.
*
* #param text String
* #param key String
* #param j int
*
* #return String
*/
public String getRandomQuote()
{
Random gen = new Random();
ArrayList< String > list = StringUtilities.getQuotes();
String quote = list.get( gen.nextInt( 6 ) );
return quote;
}
//--------------------------------------------------------------------------
/**
* Runs a simple test of CryptogramApp.
*
* #param args String[]
*/
public static void main( String args[] )
{
new Frame( 700, 500 );
new CryptogramApp( 20, 50 );
}
}
#MadProgrammer is clearly correct. Why haven't you subclassed JButton??
Now to your code,
It's not clear what error you're receiving, or what is not working for you.
Should you have
public class SubstituteButton extends RoundedRectangle implements MouseListener
and at some stage
SubstituteButton button=new SubstituteButton();
button.addMouseListener(button)
? This would connect your button to the listener.
Also, where are you adding the button to the frame?
Please post the complete code.
When running below program, I cannot reach the end of the main function...
I am new to Java, and cannot find its defects. I need your help. Thanks.
import java.util.*;
class Schedule {
public String day;
private int startTime, endTime;
public Schedule(String input_day, int input_start, int input_end) {
day = input_day;
startTime = input_start;
endTime = input_end;
}
/* clashWith: to check whether this schedule clash with a Schedule called otherSchedule
* PRE-Condition : input must be of Schedule type
* POST-Condition : return true if two Schedule clash, return false if not.
*/
public boolean clashWith(Schedule otherSchedule) {
if(this.day != otherSchedule.day || this.endTime <= otherSchedule.startTime || this.startTime >= otherSchedule.endTime)
return false;
return true;
}
}
class Module {
String code;
Schedule lecture, tutorial, lab;
public Module(String input_code, Schedule input_lecture, Schedule input_tutorial, Schedule input_lab) {
code = input_code;
lecture = input_lecture;
tutorial = input_tutorial;
lab = input_lab;
}
/* count: to count number of classes(lecture, tutorial, and lab of only this Module) on day.
* For example: when day = "Monday", lecture is on Monday, tutorial is on Monday
* but lab is on Tuesday, then return 2. (lecture and tutorial are on Monday).
* PRE-Condition :
* POST-Condition :
*/
public int count(String day) {
int num = 0;
if(lecture.day == day)
num++;
if(tutorial.day == day)
num++;
if(lab.day == day)
num++;
return num;
}
/* clashWith: to check whether this module clash with a Module called otherModule
* PRE-Condition :
* POST-Condition :
*/
public boolean clashWith(Module otherModule) {
if(lecture.clashWith(otherModule.lecture) || lecture.clashWith(otherModule.tutorial) || lecture.clashWith(otherModule.lab) )
return true;
if(tutorial.clashWith(otherModule.lecture) || tutorial.clashWith(otherModule.tutorial) || tutorial.clashWith(otherModule.lab))
return true;
if(lab.clashWith(otherModule.lecture) || lab.clashWith(otherModule.tutorial) || lab.clashWith(otherModule.lab))
return true;
return false;
}
}
class Timetable {
Vector<Module> listOfModule;
/* checkClash: to check whether otherModule clash with one of
* the modules in our timetable list.
* PRE-Condition :
* POST-Condition :
*/
public boolean checkClash(Module otherModule) {
for(Module c: listOfModule)
if(c.clashWith(otherModule))
return true;
return false;
}
/* add: to add a new module to the timetable list.
* PRE-Condition :
* POST-Condition :
*/
public void add(Module module) {
listOfModule.add(module);
}
/* count: to count number of classes on day.
* PRE-Condition :
* POST-Condition :
*/
public int count(String day) {
int count_day=0;
for(Module c: listOfModule)
count_day += c.count(day);
return count_day;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num_operation;
String code ;
Timetable userTimetable = new Timetable();
num_operation = input.nextInt();
for(int i=0;i<num_operation;i++) {
if(input.next() == "MODULE") {
code = input.next();
String day;
int start, end;
Schedule getLecSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Schedule getTutSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Schedule getLabSche = new Schedule(input.next(),input.nextInt(),input.nextInt());
Module userModule = new Module(code, getLecSche, getTutSche, getLabSche);
System.out.println("Reached line 162");
if(!userTimetable.checkClash(userModule)) {
userTimetable.add(userModule);
System.out.println("Added");
}
else
System.out.println("Clashed");
}
else if(input.next() == "COUNT") {
code = input.next();
System.out.println(userTimetable.count(code));
}
}
}
}
Found it. You're using == to compare Strings. That only compares the object reference.
Use this instead:
if (input.next().equals("MODULE"))
//...
if(input.next().equals("COUNT"))
It is also worth mentioning that this will not catch "Count", "cOunT", "Module", "module", or "mOdulE" - you may want to use equalsIgnoreCase() instead.
In Timetable, you are never assigning a value to listOfModule:
Vector<Module> listOfModule;
Which causes a NullPointerException. You need to assign a new object to that reference:
Vector<Module> listOfModule = new Vector<Module>();
I think the problem is with input.next() here.
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
UPDATE :
Removing the confusion for downvoters input.next() above is from statement if(input.next() == "MODULE") {
I have two textfield in my swing component. In one text field i need to have only numbers
(no string,empty spaces,special charaters allowed) and in another textfield i need to have only string(no numbers,empty spaces,special charaters allowed). How can i implement that..???
You can use the Pattern Class (Regular Expressions) to validate the input. A short tutorial is available here.
I am pretty sure that the basic tutorial covers all this...
"^//d+$" //The text must have at least one digit, no other characters are allowed
"^[a-zA-Z]+$" //The text must have at least one letter, no other characters are allowed
You have two choices, you can validate the text in the fields either 1) on entry or 2) when the user performs an action such as clicks a confirmation button.
For 2) npinti's answer should steer you in the right direction, just get the value of the field and validate it with a regular expression.
For 1) you might want to write a KeyListener that intercepts key presses and only allows the correct type of character for the field.
You can extend javax.swing.text.PlainDocument class, and call setDocument method textfield. Here is one of the example ;
package textfield;
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitedValuePositiveIntegerDocument extends PlainDocument {
int maxValue;
int maxLength;
Toolkit toolkit;
/**
* Constructor for the class.
* #param max maximum value of the number
*/
public LimitedValuePositiveIntegerDocument(int max){
maxValue = max;
maxLength = (""+max).length();
toolkit = Toolkit.getDefaultToolkit();
}
/**
* Inserts the input string to the current string after validation.
* #param offs offset of the place where the input string is supposed to be inserted.
* #param str input string to be inserted
* #param a attribute set
*/
#Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str == null)return;
String currentText = getText(0,getLength());
String resultText = new String();
int i;
boolean errorFound = false;
boolean deleteFirstZero = false;
int accepted=0;
for (i = 0; (i<str.length())&&(!errorFound); i++) {
if (Character.isDigit(str.charAt(i))) { /* if it is digit */
if (offs==currentText.length()) { /* calculates the resultant string*/
resultText = currentText+str.substring(0,i+1);
} else if (offs==0) {
resultText = str.substring(0,i+1)+currentText;
} else {
resultText = currentText.substring(0, offs)+str.substring(0,i+1)+currentText.substring(offs,currentText.length());
}
if (Integer.parseInt(resultText) > maxValue) {
errorFound = true;
toolkit.beep();
} else {
if ( resultText.length() == maxLength+1) {
deleteFirstZero = true;
}
accepted++;
}
} else {
errorFound = true;
toolkit.beep();
}
}
if ( accepted>0 ) { /* insert string */
super.insertString(offs, str.substring(0,accepted), a);
if (deleteFirstZero) {
super.remove(0,1);
}
}
}
/**
* Removes a part of the current string.
* #param offs offset of the place to be removed.
* #param len length to be removed
*/
#Override
public void remove(int offs, int len) throws BadLocationException{
super.remove(offs, len);
}
/**
* Returns max value of the number.
* #return max value
*/
public int getMaxValue() {
return maxValue;
}
/**
* Sets max value of the number.
* #param max maximum value of the number
*/
public void setMaxValue(int max) {
this.maxValue = max;
}
} // end of class
EDIT :
and its usage;
LimitedValuePositiveIntegerDocument doc = new LimitedValuePositiveIntegerDocument(999);
JTextField numberField = new JtextField();
numberField.setDocument(doc);
You can only enter positive numbers less than 1000, and it check while you are pressing the key..