java代码,允许在其中输入一些单词,直到我输入一个空格,然后它用破折号输出相同的字符串



我需要一个java代码,它允许在输入空格之前向其中输入一些单词,然后它输出单词之间带有短划线(-)的相同字符串。这是我的尝试:

import  javax.swing.JOptionPane;
public class tst4 {
    public static void main(String[] args) {
        String S;
        int i=0;
        do{
            S = JOptionPane.showInputDialog("input S: ");           
            while( i<S.length() ){
                         i++;
           }
        } white( (int)S != 32 );  // space is equal to 32 in ASCII
        System.out.println( S );
}

如果输入为:

thank(enter)
you(enter)
all(enter)
(space)

输出将是:

tnank-you-all

家庭作业的解决方案(不要告诉教授):

import java.io.*;
public class whatever {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer buffer = new StringBuffer();
        String str;
        while((str = in.readLine()) != null && !str.equals(" ")) {
            buffer.append(str);
        }
        System.out.println(buffer.toString().replace(" ", "-");
    }
}

您必须将它放在一个名为whatever.java的文件中。

import javax.swing.JOptionPane;
public class ReplaceSpacesWithHyphens {
    public static void main(String [] args) {
        System.out.println(JOptionPane.showInputDialog("Input String: ").trim().replace(' ', '-'));
        System.exit(0);
    }
}

此代码从JOptionPane获取输入,用连字符替换空格,然后将其打印到控制台。

因此,如果您输入,我在JOptionPane中输入了此文本,它会打印到控制台上说,I-enteredthis-text-in-the-JOptionPane

相关内容

最新更新