我需要下面的代碼來獲得BalancedString的默認構造函數,它將str初始化爲空字符串並將計數器重置爲0類的一個參數構造函數將字符串s傳遞給str並將計數器重置爲零。該BalancedString類還提供了一個布爾方法,該方法是布爾平衡()如果字符串包含括號爲什麼我的代碼只輸出字符串是平衡的
import java.util.*;
public class BalancedString {
private static String str;
public BalancedString()
{
str = "";
}
public BalancedString(String s)
{
s = "";
str = s;
}
public boolean balanced(){
return true;
}
public static void main(String[] args) {
int n = 0;
CounterFancy.setCounter(n);
Scanner input = new Scanner(System.in);
System.out.println("Enter a string that has any number of Left and right Parenthesis");
String s = input.next();
if (s.indexOf('(') != -1)
CounterFancy.incCounter();
if (s.indexOf(')') != -1)
CounterFancy.decCounter();
int counterValue = CounterFancy.getCounter();
if (counterValue == 0)
System.out.println("The string is Balanced");
else
System.out.println("The string is NOT Balanced");
input.close();
}
public String getStr()
{
return str;
}
public String setStr(String s)
{
str = s;
return str;
}
}
的平衡量,下面是其他項目,我得到了CounterFancy返回true從類,但問題是上述^^這是爲什麼只outputing它是平衡
//Joe D'Angelo
//CSC 131-03
//Chapter 10 Programming Assignment 5a.
//Takes the user's input of whether they want the counter to be negative or positive and outputs
//10 values of the user's selected input, then restarts the counter at 0
import java.util.*;
public class CounterFancy { //I messed up the first time and had to change FancyCounter to CounterFancy that is why this is changed
private static int counter;
public CounterFancy()
{
counter = 0;
}
public CounterFancy(int n){
counter = n;
}
public static int incCounter() //inc stands for increment
{
counter++;
return counter;
}
public static int decCounter() //dec stands for decrement
{
counter--;
return counter;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Press 1 for Possitive or Press 2 for Negative");
int reply = input.nextInt();
if (reply == 1)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.incCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
if (reply == 2)
{
for (int i = 1; i <=10; i ++)
System.out.println("counter: " + CounterFancy.decCounter());
CounterFancy.setCounter(5);
System.out.println("Counter: " + CounterFancy.getCounter());
}
input.close();
}
public static int getCounter()
{
return counter;
}
public static void setCounter(int n)
{
counter = 0;
}
}
如何使這些變化,我需要幫助我的老師並沒有告訴我任何事情 –
的問題非常具有誤導性:''BalancedString'永遠不會被實際使用(因此不是問題)。 – Vulcan
@Vulcan - 我想現在可以忽略'BalancedString',但我認爲OP最終會使用它。不過,我最後一段談到了這個問題的核心。 –