2013-08-22 86 views
0

在某種情況下是否有辦法從字符串中刪除變量? 例如:有兩行,每行有100,200和300垂直。 如果有人選擇100,我怎麼能得到它來刪除100,但離開200和300 ..?在某些條件下刪除變量

我還沒有嘗試過任何東西,但我已經把100,200等等作爲變量,只是在特定的樣式中打印出變量以使其看起來垂直。這些變量也是int ..

P.s這是一個危險的遊戲。

+3

使用'名單',而不是一個單一的'String'來處理,那麼,你的數據。 –

+0

第一個問題。是。這是計算機科學,你可以做任何事情! – SchautDollar

+0

@LuiggiMendoza你是什麼意思?你能詳細談談嗎?我擁有system.out.println的所有數字......並且配置爲使它看起來像是垂直的。 – jason

回答

-1

這個答案假定你有一個你想要打印的字符串,並且改變這些內容的片斷。

用空格替換變量。

首先找到你想要消除串的正確位置,使用

indexOf(String str, int fromIndex), 

的indexOf( 「100」,X);

對於x,您將列的索引放置在要從中消除的列。 然後提取子串從開始到想要消除的子串,

substring(int beginIndex,int endIndex);

,並用其替換成原:

replace(CharSequence target+"100", CharSequence replacement+" "); 

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

0

閱讀你的問題,看來你心裏有這樣的事情:

int c1_100=100, c1_200=200, c1_300=300, c2_100=100, c2_200=200, c3_300=300; 
System.out.println(c1_100+"/t"+c2_100+"/t"+c1_200+"/n"+c2_200+"/t"+c1_300+"/t"+c2_300+"/t"+); 

如果你想保留這個結構,你可以用字符串代替:

String c1_100="100", c1_200="200", c1_300="300", c2_100="100", c2_200="200", c3_300="300"; 

,當玩家選擇,例如問題c2_200,你可以做

c2_100=" "; 

但這不是來組織代碼的最佳方式。 如果你想在一個類似表格的形式打印出來的數據,你可以使用2維數組:

int questions[][]={{100, 200, 300}, {100, 200, 300}, {100, 200, 300}}; 

,然後打印出來在一個循環:

for(int i=0, i<3; i++){ 
    for(int k=0; k<3; k++){ 
     if(question[k][i]>0){ //test if you assigned 0 to the chosen question 
     System.out.print(question[k][i]+"/t"); 
     } 
     System.out.println("/n"); 
    } 
} 

而且每次一用戶選擇一個問題,在其中放入0。舉例來說,如果他選擇在第2列和值100的問題,不要

questions[1][0]=0; 

一個更好的解決辦法是不要硬編碼值,但使用數組中的位置,以此來了解值:

boolean questions[][]; 
    questions=new boolean[5][3]; //here I created 5 columns and 3 rows 
    //initialize 
    for(int i=0; i<questions.length; i++){ 
      for(int k=0; k<questions[0].length; k++){ 
       questions[i][k]=true; 
      } 
    } 

    //print 
     for(int i=0; i<questions[0].length; i++){ 
       for(int k=0; k<questions.length; k++){ 
        if(questions[k][i]){ //test if you assigned true to the chosen question 
        System.out.print(100*(i+1)+"\t"); 
        } 
        else{ 
         System.out.print(" "+"\t"); 
        } 
       } 
       System.out.println(); 
     } 

和關閉過程當選擇了一個問題:

questions[x][y]=false; 

輸出:

100 100 100 100 100 
200 200 200 200 200 
300 300 300 300 300 

並經過

questions[1][1]=false; 

100 100 100 100 100 
200  200 200 200 
300 300 300 300 300