so i'm doing a project for my Computer Science class where i'm building a wheel of fortune game, and for some reason im having an error with debugging my code. if anyone can help, id be very greatful.
** full code in comments wont let me post it ***
public class WheelOfFortune {
private String Hidden;
public WheelOfFortune(String g) {
Hidden = g;
}
public String getHint(String g) {
String letter, HL, result = "";
int x = g.length(), y = 0;
for (int i = 0; i < x; i++) {
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) {
result += letter;
y = Hidden.indexOf(letter);
}
if (y == -1) result = "*";
else result = "+";
return result;
}
}
}
public class Puzzle {
public static void main(String[] args) {
WheelOfFortune guess = new WheelOfFortune("HARPS");
String turn = guess.getHint("AAAAA");
System.out.println(turn);
}
}
Your code didn't even compile because of a missing return statement after the for loop. With this and other errors corrected, your getHint() is:
public String getHint(String g)
{
String letter, HL, result = "";
int x = g.length();
for (int i = 0; i < x; i++)
{
letter = g.substring(i, i + 1);
HL = Hidden.substring(i, i + 1);
if (letter.equals(HL)) result += letter;
else
if (Hidden.contains(letter)) result += "+";
else
result += "*";
}
return result;
}
Related
I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.
I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}
I have a program which takes Giraffes from a text file, creates an ArrayList and LinkedList out of them (redundant, I know... LinkedList was a requirement of the second part of the assignment and I liked my ArrayList), sorts out who their parents are, and then is supposed to print a VBA macro out to a file.
The file (D:\\Java\\Macro.txt) is created, but it isn't populated with anything. Why isn't anything getting printed to the file? I think that there is an issue creating an array to return to the main function though.
I suspect that the problem is within the GetYearGroup method in the Herd Class, and the way that it is interfacing with the PrintWriter located on lines 51-83 of the Main class.
Here is the code:
HW4_Name.java (main)
package giraffe;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class HW4_Name {
public static void main(String[] args) throws IOException {
ArrayList<Giraffe> giraffes = new ArrayList<>();
String temp[] = new String[13];
String header = "";
String fileLocation = "theHerd.txt";
File textFile = new File(fileLocation);
Scanner in = new Scanner(textFile);
if (textFile.canRead()) {
header = in.nextLine();
while (in.hasNextLine()) {
temp = in.nextLine().split("\\t", 13);
giraffes.add(new Giraffe(temp));
}
}
Herd herd = new Herd();
for(int i = 0; i < giraffes.size(); i++){
Giraffe g = giraffes.get(i);
herd.Add(g);
}
int nGiraffes = herd.Size();
for(int i = 0; i < nGiraffes; i++){
Giraffe g = herd.GetAt(i);
int nSire = g.getSireId();
if (nSire != -1){
g.setSire(herd.Find(nSire));
}
int nDam = g.getDamId();
if (nDam != -1){
g.setDam(herd.Find(nDam));
}
}
in.close();
PrintWriter pw = new PrintWriter("C:\\Java\\Macro.txt");
int nHeight = 500;
int nWidth = 900;
int nYearHeight = nHeight / 13;
int nRectangle = 0;
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
Giraffe[] ThisGroup = herd.GetYearGroup(nLowYear, nLowYear + 5);
int nThisGroup = ThisGroup.length;
int nXSpacing = nWidth / (nThisGroup + 1);
int nYPos = 10 + nYearHeight * i;
for(int j = 0; j < nThisGroup; j++){
nRectangle++;
int nXPos = 10 + nXSpacing/2 + nXSpacing * j;
Giraffe g = ThisGroup[j];
g.setRectangle(nRectangle);
String strName = g.getName();
pw.println("Call Box(" + nXPos + ", " + nYPos + ", \"" +strName + "\")");
}
}
for(int i = 0; i < nGiraffes; i++){
Giraffe g = herd.GetAt(i);
Giraffe gSire = g.getSire();
if (gSire != null){
int nParentRectangle = gSire.getRectangle();
nRectangle = g.getRectangle();
if (nParentRectangle > 0 && nRectangle > 0){
pw.println("Call DadLine(" + nParentRectangle + ", " + nRectangle + ")");
}
}
Giraffe gDam = g.getDam();
if(gDam != null){
int nParentRectangle = gDam.getRectangle();
if (nParentRectangle > 0 && nRectangle > 0){
pw.println("Call MomLine(" + nParentRectangle + ", " + nRectangle + ")");
}
}
}
pw.close();
}
}
Giraffe.java
package giraffe;
import java.util.ArrayList;
public class Giraffe extends Object {
private String birthLocation, subSpecies, zoo, city, state, event, name,
localId, sex, eachGiraffe;
private int gId, birthYear, sireId, damId, gRectangle;
private Giraffe gSire, gDam;
public Giraffe(String array[]){
this.sex = String.format("%-1s",array[1]);
this.birthLocation = String.format("%-12s",array[5]);
this.localId = String.format("%-7s",array[6]);
this.name = String.format("%-20s",array[7]);
this.subSpecies = String.format("%-14s",array[8]);
this.zoo = String.format("%-35s",array[9]);
this.city = String.format("%-17s",array[10]);
this.state = String.format("%-13s",array[11]);
this.event = String.format("%-7s",array[12]);
this.gId = Integer.parseInt(array[0]);
this.birthYear = Integer.parseInt(array[2].substring(0,4));
if(array[3].equals("WILD") || array[3].equals("UNK")){
this.sireId = -1;
}
else{
this.sireId = Integer.parseInt(array[3]);
}
if(array[4].equals("WILD") || array[4].equals("UNK")){
this.damId = -1;
}
else{
this.damId = Integer.parseInt(array[4]);
}
}
public String getName(){
return this.name;
}
public int getId(){
return gId;
}
public int getBirthYear(){
return birthYear;
}
public int getSireId(){
return sireId;
}
public int getDamId(){
return damId;
}
public Giraffe getSire(){
return gSire;
}
public int getRectangle(){
return gRectangle;
}
public Giraffe getDam(){
return gDam;
}
public void setSire(Giraffe nSire){
this.gSire = nSire;
}
public void setDam(Giraffe nDam){
this.gDam = nDam;
}
public void setRectangle(int nRectangle){
this.gRectangle = nRectangle;
}
public String toString(){
eachGiraffe = ("" + this.gId);
return eachGiraffe;
}
}
Herd.java
package giraffe;
public class Herd extends LinkedList{
public Herd(){
}
public void Add(Giraffe g){
InsertRight(g);
}
public Giraffe Find(int idNumber){
Giraffe g = null;
Node currNode = start;
while(currNode != null && currNode.o.getId() != idNumber){
currNode = currNode.next;
}
if(currNode.o.getId() == idNumber){
g = currNode.o;
}
return g;
}
public Giraffe GetAt(int nIndex){
Giraffe g = null;
Node currNode = start;
for(int i = 0; i < nIndex; i++){
if(currNode != null){
currNode = currNode.next;
}
}
g = currNode.o;
return g;
}
public Giraffe[] GetYearGroup(int nBegin, int nEnd){
int nGiraffes = Size();
int nInGroup = 0;
for(int i = 0; i < nGiraffes; i++){
Giraffe g = GetAt(i);
int nBirthYear = g.getBirthYear();
if (nBegin <= nBirthYear && nBirthYear < nEnd){
nInGroup++;
}
}
Giraffe[] gary = new Giraffe[nInGroup];
nInGroup = 0;
for(int i = 0; i < nGiraffes; i ++){
Giraffe g = GetAt(i);
int nBirthYear = g.getBirthYear();
if(nBegin <= nBirthYear && nBirthYear < nEnd){
gary[nInGroup] = g;
nInGroup++;
}
}
return gary;
}
}
LinkedList.java
package giraffe;
public class LinkedList {
protected Node start;
private int errorReturn;
public LinkedList(){
start = null;
}
public LinkedList(int errorValue){
start = null;
errorReturn = errorValue;
System.out.println(errorReturn);
}
public boolean isEmpty(){
return (start == null);
}
public void InsertRight(Giraffe data){
Node currNode;
if (start == null){
start = new Node(data,start);
}
else{
currNode = start;
while (currNode.next != null){
currNode = currNode.next;
}
currNode.next = new Node (data, null);
}
}
public int Size(){
int length = 0;
Node currNode = start;
while(currNode != null){
length++;
currNode = currNode.next;
}
return length;
}
public void Display(){
Node currNode = start;
System.out.println("List contents: ");
while (currNode != null){
currNode = currNode.next;
}
System.out.println("--------------------------");
}
}
Node.java
package giraffe;
public class Node {
Giraffe o;
Node next;
public Node(Giraffe giraffe, Node nextNode){
o = giraffe;
next = nextNode;
}
}
Solution
Thank you to durron597 for pointing out that the birthYear function was not comparable to the GetYearGroup function.
Replacing:
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
With:
for(int i = 0; i < 13; i++){
int nLowYear = 1950 + 5 * i;
Resolved the issue.
I see two problems, both of which could result in the things you're seeing:
You are outputting to the C:\\Java\\Macro.txt directory, but you are using a relative path to find your theHerd.txt. Try changing your theHerd.txt file to an absolute path, or use Class.getResourceAsStream() if the file is on your classpath.
Use a debugger to see if the Giraffe objects are getting created at all
Your birth year check seems really weird:
for(int i = 0; i < 13; i++){
int nLowYear = 50 + 5 * i;
Giraffe[] ThisGroup = herd.GetYearGroup(nLowYear, nLowYear + 5);
This is only going to check years in the range 50, 55, up to 115. However, in your Giraffe class, you do this:
this.birthYear = Integer.parseInt(array[2].substring(0,4));
This is only going to work (i.e. not throw an ArrayIndexOutOfBounds exception) for 4 digit date years, none of which are in the range 50-115. However, if you set your year to a value like 0073 (you must put the leading zeroes) then your program will print results like Call Box(235, 162, "GiraffeName "). You probably want to change that 50 to 1950.
Your program has other code smells; I suggest reading things like (in order of increasing time commitment):
Java Encapsulation Concept not clear
Java naming conventions
Single Responsibility Principle
Clean Code, by Robert Martin
But these two bits of code should get you started.
I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.
The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();