下面的方法應該創建兩個隨機的字符串變量並打印它們。在這一點上,它們應該是相同的。Java方法不工作
public static void main(String[] args){
ScalesSolution s1 = new ScalesSolution(10);
s1.println();
ScalesSolution s2 = new ScalesSolution(s1.getSol());
s2.println();
}
的ScalesSolution類:
import java.util.*;
public class ScalesSolution
{
private String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
//Code goes here
//Create a random binary string of just ones and zeros of length n
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public double ScalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
int n = scasol.length();
//Code goes here
//Check each element of scasol for a 0 (lhs) and 1 (rhs) add the weight wi
//to variables lhs and rhs as appropriate
return(Math.abs(lhs-rhs));
}
public void smallChange(int n)
{
Random rand = new Random();
int p = (rand.nextInt(n) - 1);
// Checks if p < 0. If so, then p will not have 1 subtracted from it.
if(p < 0){
p = (rand.nextInt(n));
}
String x = new String();
x = scasol.substring(0, p);
if (scasol.charAt(p) == '0')
scasol.replace('0', '1');
else if (scasol.charAt(p) == '1')
scasol.replace('1', '0');
scasol = x;
}//End smallChange()
public String getSol(){
return(scasol);
}//End getSol()
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
輸出是空白的 - 我在做什麼錯?
謝謝。
謝謝,現在全部解決。 – MusTheDataGuy 2011-03-22 18:01:01