Edit. thank you.
I have an array of 'normal' vehicles and 'large' vehicles. I have an assignment requiring me to divide them up to contribute to a far larger app.
One array for the large vehicles, one for the normal vehicles containing all the info for each element. ArrayLists are not permitted as my instructor is teaching us fundamentals.
Sample of the array
27723 4/09/61 large 7337
28507 22-02-1983 large 7055
28558 1/05/70 normal 3518
//On button press
//recieve single item from array from main and test it
//array in main will be looped for all elements.
public String loadVehicle(Vehicle v) {
String res = Constants.OK;
boolean normBool = false;
boolean largeBool = false;
//if both arrays are full , stop the method call in the main form
if (normBool && largeBool){return Constants.ERROR;}
//if vehicle size is normal, fill the normal veh array
if(v.getSize().equals(Constants.NORMAL_SIZE))
{
for(int i = 0; i<normalVehicles.length; i++)
{
//if norm veh array element is null, add the appropriate value to it
if(normalVehicles[i] == null){normalVehicles[i] = v;}
else{normBool = true;}
}
}
//if veh size is large put it in the large veh array
else if(v.getSize().equals(Constants.LARGE_SIZE))
{
for(int iL = 0; iL<largeVehicles.length; iL++)
{
if(largeVehicles[iL] == null){largeVehicles[iL] = v;}
else{largeBool = true;}
}
}
return res;
}//end method
Seems you cannot use builtin LinkedList class too, then do this:
Add the following code in your Vehicle class:
class Vehicle(){
//YOUR OTHER PIECES OF CODES ...
private static Vehicle firstLargeVehicle;
private Vehicle nextLargeVehicle;
private int index;
public void setIndex(int index){
this.index = index;
if(index == 0) Vehicle.firstLargeVehicle = this;
}
public int getIndex(){
return index;
}
public void setNextLargeVehicle(Vehicle nextLargeVehicle){
this.nextLargeVehicle = nextLargeVehicle;
}
public Vehicle getNextLargeVehicle(){
return nextLargeVehicle;
}
public addLargeVehicle(Vehicle newVehicle){
this.nextLargeVehicle = newVehicle;
newVehicle.setIndex(index + 1);
}
public getListSize(){
Vehicle lastOne = this;
while (lastOne.getNextLargeVehicle() != null){
lastOne = lastOne.getNextLargeVehicle();
}
return lastOne.getIndex() + 1;
}
public static Vehicle[] largeVehiclesToArray(){
Vehicle[] result = new Vehicle[firstLargeVehicle.getListSize()]();
Vehicle pointer = firstLargeVehicle;
for (int counter = 0; pointer != null; counter ++){
result[counter] = pointer;
pointer = pointer.getNextLargeVehicle();
}
return result;
}
}
And in your main loop, do something like the following code:
Vehicle vehicle = null;
for(Vehicle newVehicle : allVehicles) {
if (newVehicle.isLarge()){
if (vehicle == null) {
vehicle = newVehicle;
vehicle.setIndex(0);
}else{
vehicle.addLargeVehicle(newVehicle));
}
}
}
Vehicle[] largeVehicles = Vehicle.largeVehiclesToArray();
And the same story goes for normal vehicles.
Any question ?
You can write your loops like this:
for(int i = 0; i < normalVehicles.length; i++)
{
if(normalVehicles[i] == null)
{
normalVehicles[i] = v;
break;
}
}
// if last slot isn't null then it's full
normBool = normalVehicles[normalVehicles.length-1] != null;
Full Disclosure: This was an assignment, it has been marked already, but I want to understand why I'm getting this error.
I'm having some issues understanding why junit.framework.AssertionFailedError is being thrown. Normally when errors occur I could at least look at the stack trace and see what is happening. In this case, the output console shows this:
Testcase: testIsCorrectMCQ(mr_3.myTester): FAILED
null
junit.framework.AssertionFailedError
at mr_3.MyTester.testIsCorrectMCQ(Assign03Tester.java:207)
testIsCorrectMCQ(mr_3.MyTester): FAILED
In the test result tab in NetBeans, copying the stack trace gives me:
junit.framework.AssertionFailedError
at mr_3.myTester.testIsCorrectMCQ(myTester.java:207)
In the tester file, I have this:
#Test
public void testIsCorrectMCQ() {
System.out.println("isCorrect of MCQ");
MCQuestion instance = new MCQuestion(1,"Capital city of Canada is", 'A',
"Ottawa", "Vancouver", "New York", "Toronto");
assertFalse(instance.isCorrect("B"));
assertTrue(instance.isCorrect("A")); // line 207
}
My isCorrect method is this:
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
Any help in understanding what is happening is greatly appreciated.
Edit 1 : My MCQuestion source code
public class MCQuestion extends Question {
private char answer;
private String[] options;
public MCQuestion() {
super();
questionType = QuestionType.MULTIPLE_CHOICE;
}
public MCQuestion(int id, String text, char answer, String... options) {
super(id, text);
setOptions(options);
setAnswer(answer);
questionType = QuestionType.MULTIPLE_CHOICE;
}
public String[] getOptions() {
String[] getOptions = new String[this.options.length];
System.arraycopy(this.options, 0, getOptions, 0, this.options.length);
return getOptions;
}
public void setOptions(String... options) {
if (options.length > 0) {
this.options = new String[options.length];
for (int i = 0; i < options.length; i++) {
if (options[i].isEmpty())
throw new IllegalArgumentException("You have nothing in this option");
else
this.options[i] = options[i];
}
}
else throw new IllegalArgumentException("You have no options set");
}
public char getAnswer() {
return this.answer;
}
public void setAnswer(char ans) {
ans = Character.toLowerCase(ans);
int index = ans - 97;
if (Character.isLetter(ans) && index >= 0 && index < this.options.length)
this.answer = ans;
else throw new IllegalArgumentException(ans + " is not a valid answer option");
}
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
#Override
public String toString() {
String option = "";
if (this.options.length == 0)
option = "No options added, yet!";
else {
char index = 'a';
for (String e: options)
option += index + ") " + e + "\n";
}
return (super.toString() + "\n" + option);
}
}
You execute ans = Character.toLowerCase(ans); for whatever reason in your setAnswer() method before saving it in this.answer. This means that (userGuess.charAt(0) == this.getAnswer()) will return false when you provide the answer in upper case, but compare it with the stored lower case character.
Depending on if you want case insensitive answers or not, you should add or remove the Character.toLowerCase() call to your isCorrect() method as well.
I am trying to get my bet system to detect if the input numbers are duplicates. When you run the program, press 2 on the "for box" bet and follow instructions from there. The issue lies in the winlose duplicate and also for the non duplicate. I don't know how I am supposed to fix the issue.
Error stacktrace :
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at numbersgame.Test.winLoseBetDuplicate(NumbersGame.java:190)
at numbersgame.Test.checkDuplicate(NumbersGame.java:167)
at numbersgame.Test.WinLoseBox(NumbersGame.java:134)
at numbersgame.Test.getValues(NumbersGame.java:117)
at numbersgame.NumbersGame.main(NumbersGame.java:24)
C:\Users\cymmm1\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
Code :
/*
* 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 numbersgame;
import java.lang.reflect.Array;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* #author cymmm1
*/
public class NumbersGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Test numbers = new Test();
numbers.getValues();
boolean win = numbers.win; //this checks if you won, either as a duplicate or not.
if (win) {
System.out.println("You won");
switch (numbers.bet_Type) {
case 1:
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 600 + " back.");
break;
case 2:
if (numbers.dupwin) {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 200 + " back.");
} else {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 100 + " back.");
}
break;
}
} else {
System.out.println("Sorry, you lost $" + numbers.bet_Amount + " dollars");
}
System.exit(0);
}
}
class Test {
public int bet_Type;
public int bet_Amount;
public int player_Number;
public int winning_Number;
private JOptionPane panel;
public boolean win;
public List<Integer> digits = new LinkedList<>();
List<Integer> digits2 = new LinkedList<>();
public void getValues() {
panel = new JOptionPane();
this.bet_Type = (Integer.parseInt(panel.showInputDialog("What is the bet type. 1 for straight, 2 for box")));
this.bet_Amount = (Integer.parseInt(panel.showInputDialog("How much is the bet")));
boolean bad = true;
while (bad) {
this.player_Number = (Integer.parseInt(panel.showInputDialog("What is the player's Number. 3 numbers must be inputted")));
int playerNumCopy = this.player_Number;
while (playerNumCopy > 0) {
digits.add(0, playerNumCopy % 10);
playerNumCopy = playerNumCopy / 10;
}
int lengthOfNum = digits.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
bad = true;
while (bad) {
this.winning_Number = (Integer.parseInt(panel.showInputDialog("What is the winning Number")));
int winningnumbercopy = this.winning_Number;
while (winningnumbercopy > 0) {
digits2.add(0, winningnumbercopy % 10);
winningnumbercopy = winningnumbercopy / 10;
}
int lengthOfNum = digits2.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
//========END OF CHECK FOR PROPER NUMBERS=================================
//Now to check for type of bet and se the method appropriate
if (this.bet_Type == 1) {
win = WinLoseStraight();
} else {
win = WinLoseBox();
}
}
private boolean WinLoseStraight() {
if (this.player_Number == this.winning_Number) {
return true;
} else {
return false;
}
// this goes back to getValues
}
private boolean WinLoseBox() {
//this checks for duplicates. if it isnt a duplicate then check for a box non-dup
boolean duplicatewin = checkDuplicate();
if (duplicatewin) { //you either won with a duplicate number or nonduplicate. check Duplicate does to things at once
return true;
} else {
return false;
}
}
public boolean duplicate;
public boolean dupwin;
//this checks for duplicated numbers
public boolean checkDuplicate() {
duplicate = false;
int[] array = new int[digits.size()];
int i = 0;
for (int numbers : digits) {
array[i] = numbers;
System.out.println(array[i]);
i++;
}
for (int j = 0; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (array[k] == array[j]) {
duplicate = true;
System.out.println(array[k] + " equals " + array[j]);
break; //if duplicated found, it will exit out of the for loop
}
}
if (duplicate) {
System.out.println("we found duplicate.");
dupwin = winLoseBetDuplicate(); //if it has duplicated numbers, it will check if your numbers match up
break;
} else {
dupwin = winLostBetNonDuplicate();
}
}
return dupwin; //this will return if you have won the prize with a duplicated number. goes back to getValues
}
private boolean winLoseBetDuplicate() {
/*how this method works is we make a linked list.
use a advanced for loop and when we encounter
a hit, we remove the number from it.
if there is still a number in the linkedlist of
player number it is a lose. we still have digits as a linked list. */
//
boolean won = false;
boolean match;
for (int digitsnumbers : digits) {
System.out.println("Checking the number: " + digitsnumbers);
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits.remove(digits.indexOf(digitsnumbers));
digits2.remove(digits2.indexOf(digits2numbers));
System.out.println("we found a duplicated numer match. Removing from choosing. ");
System.out.println(digits);
System.out.println(digits2);
match = true;
} else {
match = false;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
private boolean winLostBetNonDuplicate() {
boolean won;
for (int digitsnumbers : digits) {
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits2.remove(digits.indexOf(digits2numbers));
digits.remove(digits.indexOf(digitsnumbers));
break;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
}
I am working on this question. It seems like that I have found the right answer and returns true but then it is overwritten by false.. Newbie in Java, sorry if it is a dummy question.. How do I just return true?
Thank you in advance
Question
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
import java.util.HashSet;
import java.util.Set;
public class Hi {
public static void main(String[] args) {
String str = "leetcode";
Set<String> set = new HashSet<String>();
set.add("leet");
set.add("code");
boolean b = wordBreak(str, set);
System.out.println("b is " + b);
}
public static boolean wordBreak(String s, Set<String> wordDict) {
if(s.length() == 0 || wordDict.isEmpty()) {
return false;
}
return helper(s, wordDict, 0);
}
public static boolean helper(String s, Set<String> wordDict, int index) {
if(index == s.length()) {
System.out.println("1 is called.. ");
return true;
}
int curIndex = index;
System.out.println("curIndex is " + curIndex);
while(index < s.length()) {
//System.out.println("s.length() is " + s.length());
curIndex++;
if(curIndex > s.length()) {
System.out.println("2 is called.. ");
//return false;
return false;
}
if(wordDict.contains(s.substring(index, curIndex))) {
System.out.println(s.substring(index, curIndex) + " curIndex is " + curIndex);
helper(s, wordDict, curIndex);
}
}
System.out.println("3 is called.. ");
return false;
}
output:
curIndex is 0
leet curIndex is 4
curIndex is 4
code curIndex is 8
1 is called..
2 is called..
2 is called..
b is false
This might not answer your question but I just mentioned an approach, and by no means I'm saying that my approach is better or more optimal.
In your code, there is no return true statement. The code does the right work but at the very end, since loop doesn't break anywhere, it always returns false. I mean you need to return true somewhere based on some condition and one of such conditions I mentioned in my below example.
private static boolean test(String str, Set<String> set) {
int i = 1;
int start = 0;
List<String> tokens = new ArrayList<String>();
while (i <= str.length()) {
String substring = str.substring(start, i);
if (set.contains(substring)) {
tokens.add(substring);
start = substring.length();
}
i++;
}
String abc = "";
for (String a : tokens) {
abc = abc + a;
}
System.out.println(abc);
if (abc.equals(str)) {
return true;
} else {
return false;
}
}
Below is the screenshot from debug trace from within debugger.
I want to convert a string input like 2,3,6,7,8,10,12,14,15,16 to 2-3,6-8,10,12,14-16 using java
I tried using the below code
Vector ar=new Vector();
int lastadded=0;
String ht="";
String [] strarray=str.split(",");
strarray=sortArray(strarray);
Vector intarray=new Vector();
for(int i=0;i<strarray.length;i++)
{
int temp=1;
for(int j=1;j<=intarray.size();j++)
{
if(Integer.parseInt(strarray[i])==Integer.parseInt(intarray.get(j-1).toString()))
{
temp=0;
}
}
if(temp==1)
{
intarray.add(Integer.parseInt(strarray[i]));
ar.add(Integer.parseInt(strarray[i]));
}
}
ht="";
String strdemo="";
for(int i=0;i<intarray.size();i++)
{
if(ht=="")
{
ht=ar.get(i)+"";
lastadded=i;
}
else
{
strdemo=(String)ht;
if(strdemo.length()==ar.get(0).toString().length())
{
if(Integer.parseInt(strdemo.substring(0))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo+"-"+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
else if(strdemo.length()==3)
{
strdemo=(String)ht;
if(Integer.parseInt(strdemo.substring(strdemo.length()-1,strdemo.length()))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo.substring(0,strdemo.length()-2)+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}//Else IF
else{
strdemo=(String)ht;
int de=1;
int ddd=lastadded;
if(ddd==Integer.parseInt(ar.get(i).toString())-1)
{
int lastaddedlen=(lastadded+"").length();
String symbol=strdemo.substring(strdemo.length()-lastaddedlen-1,strdemo.length()-lastaddedlen);
if(symbol.equalsIgnoreCase("-"))
strdemo=strdemo.substring(0,strdemo.length()-lastaddedlen-1)+"-"+Integer.parseInt(ar.get(i).toString());
else
strdemo=strdemo+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
}
}
Here sortArray function sorts the array descending and returns
protected static String[] sortArray(String ss[])
{
String temp;
for(int i=0;i<ss.length;i++)
{
for(int j=0;j<ss.length;j++)
{
if(Integer.parseInt(ss[i])<Integer.parseInt(ss[j]))
{
temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;
}
}
}
return ss;
}
I am not getting consistant results for some inputs for example for the below case
2,3,6,7,8,10,12,14,15,16 it gives 2-3,6-8,10,12,14-16 (which is correct)
while for 2,4,5,6,7,8,10,12,14,15,16 it gives 2-8,10,12,14-16 (which actually should have been 2,4-8,10,12,14-16)
Where does the code go inconsistent is what I need to find out..
This is pretty ugly and verbose in Java, but here is a version. Note, it uses StringUtils from Spring at the very end for the trivial but also ugly process of converting a String collection to a comma delimited string.
The key is to use a separate class to model the numeric ranges. Let this class know how to turn itself into a String. Then you won't have so much logic around appending to a StringBuilder.
Also, try to think in terms of collections. This always makes things clearer. The pseudo-code is something like: String becomes List<Integer> becomes List<Range> and finally becomes String.
public class Ranges {
// A class that models a range of integers
public static class Range {
private int low;
private int high;
public Range(int low, int high) {
this.low = low;
this.high = high;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
#Override
public String toString() {
return (low == high) ? String.valueOf(low) : String.format("%d-%d", low, high);
}
}
public static void main(String[] args) {
String input = "2,3,6,7,8,10,12,14,15,16";
// Turn input string into a sorted list of integers
List<Integer> inputNumbers = new ArrayList<Integer>();
for (String num : input.split(",")) {
inputNumbers.add(Integer.parseInt(num));
}
Collections.sort(inputNumbers);
// Flatten list of integers into a (shorter) list of Ranges
Range thisRange = null; // the current range being built
List<Range> ranges = new ArrayList<Range>();
for (Integer number : inputNumbers) {
if (thisRange != null && number <= thisRange.getHigh() + 1) {
// if we are already building a range (not null) && this new number is
// the old high end of the range + 1, change the high number.
thisRange.setHigh(number);
} else {
// create a new range and add it to the list being built
thisRange = new Range(number, number);
ranges.add(thisRange);
}
}
// Join List<String> into a single String
String result = StringUtils.collectionToCommaDelimitedString(ranges);
System.out.println("result = " + result);
}
}
Here is my implementation. Hope this help.
You have to pass these values
e.g int[] a = {2,3,4,5,6,7,8,10,12, 14,15,16,18,19,21,22,26};
to the following method.
public List<String> listIntRange(int[] values)
{
List<String> intRangeList = new ArrayList<String>();
int first = 0;
int current = 0;
int prev = 0;
int count = 0;
if (values == null || values.length < 1)
return intRangeList;
first = prev = values[0];
int index = 1;
boolean range = false;
for(index = 1; index < values.length; index++)
{
current = values[index];
if(current - prev == 1)
{
range = true;
prev = current;
continue;
}
if(range == true)
{
intRangeList.add(first + "-" + prev);
}
else
{
intRangeList.add("" + first);
}
first = current;
prev = current;
range = false;
}
if(range == true)
{
intRangeList.add(first + "-" + current);
}
else
{
intRangeList.add("" + current);
}
return intRangeList;
}
Output is as follows, when print out the values from intRangeList:
2-8,10,12,14-16,18-19,21-22,26,
Please ignore last comma ','.