Java字符串操作 x行,每行含有y个元素。

huangapple go评论78阅读模式
英文:

Java string manipulation x number of lines with y element

问题

以下是您提供的内容的翻译:

示例

x=3 y=3
用户输入:
101
100
000

然后如何将字符串分离以将每个值输入不同的单元格。

编辑 1:

import java.util.Scanner;

public class RedVsGreen {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x, y;
        String line;
        String[] lineVector = new String[3];

        while (lineVector.length != 2 || (Integer.parseInt(lineVector[0]) >= 1000 || Integer.parseInt(lineVector[0]) <= 1)
                || (Integer.parseInt(lineVector[1]) <= 1 || Integer.parseInt(lineVector[1]) >= 1000)) {
            System.out.print("请输入x和y,用逗号分隔(大于1且小于1000):");
            // 读取x和y
            line = scanner.nextLine();
            // 通过逗号分隔所有值
            lineVector = line.split("\\s*,\\s*");
        }

        // 解析值为整数
        x = Integer.parseInt(lineVector[0]);
        y = Integer.parseInt(lineVector[1]);

        for (int i = 0; i < x; i++) {

        }
    }
}

请注意,代码中可能存在其他错误,需要根据具体需求进行调试和修复。

英文:

Easiest way to explain my problem is to give you an example. Lets say I have 2 values X and Y. I wan't to ask the user to enter X lines with Y elements and they should be only 0s and 1s and then enter that values in array.

Example

x=3 y=3
User input:
101
100
000

And then how to separate string to enter each value in different cell.

EDIT 1:

import java.util.Scanner;

public class RedVsGreen {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int x,y;
        String line;
        String[] lineVector = new String[3];

 while ( lineVector.length !=2 || (Integer.parseInt(lineVector[0]) &gt;= 1000 || Integer.parseInt(lineVector[0]) &lt;= 1)
                ||  (Integer.parseInt(lineVector[1]) &lt;= 1 || Integer.parseInt(lineVector[1]) &gt;= 1000)){
            System.out.print(&quot;Please enter x and y, comma separated (more than 1 and less than 1000):&quot;);
            //read x,y
            line = scanner.nextLine();
            //separate all values by comma
            lineVector = line.split(&quot;\\s*,\\s*&quot;);
        }

        //parsing the values to Integer
        x = Integer.parseInt(lineVector[0]);
        y = Integer.parseInt(lineVector[1]);

        for (i = 0 ; i &lt; x; i++){
            
        }
//
//            int[][] field = new int[x][y];
//            for (int row = 0; row &lt; field.length; row++) {
//                System.out.println(&quot;&quot;);
//                for (int col = 0; col &lt; field[row].length; col++) {
//                    field[row][col] = 9; //dummy value
//                    System.out.print(field[row][col] + &quot; &quot;);
//                }
//            }
//
    }
}

答案1

得分: 1

**接收 x 和 y**

在这个问题中你的 while 条件过于复杂使用 do while 格式更适合因为你至少会获取一次值而且代码更可读

另外你可以使用 x 来代替 `Integer.parseInt(lineVector[0])`(y 也是同样的道理),而不是重复这个过程这样可以缩短条件判断

```java
String line;
String[] lineVector;
int x = -1, y = -1;

do {
    System.out.print("请输入 x 和 y,以逗号分隔(大于1且小于1000):");

    line = scanner.nextLine();
    lineVector = line.split("\\s*,\\s*");

    if (lineVector.length != 2)
        continue;

    x = Integer.parseInt(lineVector[0]);
    y = Integer.parseInt(lineVector[1]);
} while (!((x > 1 && x < 1000 && y > 1 && y < 1000)));

首先,我删除了 lineVector 的初始值,因为在这种情况下初始化是不必要的(你之前需要这样做是因为它出现在 while 条件中)。

我将 xy 初始化为 -1(任何不在我们范围内的数字都可以),以确保 do-while 条件在为这两个数字提供适当值之前得到满足。

检查二进制值的函数

创建一个函数来检查字符串值是否为二进制。

public static boolean isBinary(String s) {
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (c != '0' && c != '1')
            return false;
    }
    return true;
}

接收二进制值

String[] binaries = new String[x];

System.out.println("输入长度为 " + y + " 的二进制值:");

// 获取二进制值
for (int i = 0; i < x; ++i) {
    binaries[i] = scanner.nextLine();

    while (!isBinary(binaries[i]) || binaries[i].length() != y) {
        System.out.println("无效的二进制值。请重新输入新值:");
        binaries[i] = scanner.nextLine();
    }
}

接收二进制值,并在无效时继续要求输入。

填充二维数组

int[][] field = new int[x][y];

for (int i = 0; i < x; ++i) {
    System.out.println();
    for (int j = 0; j < y; ++j) {
        char c = binaries[i].charAt(j);
        if (c == '0')
            field[i][j] = 0;
        else
            field[i][j] = 1;

        System.out.print(field[i][j] + " ");
    }
}

在这里,Integer.parseInt 是不必要的,因为只有两个可能的值(0 和 1)。


<details>
<summary>英文:</summary>

**Receiving x and y**

    while ( lineVector.length !=2 ...)

Your while condition is too complicated, a do while format matches this problem much better since you are going to get the values at least once, and the code is more readable.

Also you could have used x instead of `Integer.parseInt(lineVector[0])` (same for y) instead of repeating the process, this would have shortened the condition.
    

    String line;
    String[] lineVector;
    int x = -1, y = -1;

        do {
            System.out.print(&quot;Please enter x and y, comma separated (more than 1 and less than 1000):&quot;);

            line = scanner.nextLine();
            lineVector = line.split(&quot;\\s*,\\s*&quot;);

            if(lineVector.length != 2)
                continue;

            x = Integer.parseInt(lineVector[0]);
            y = Integer.parseInt(lineVector[1]);
        } while (!((x &gt; 1 &amp;&amp; x &lt; 1000 &amp;&amp; y &gt; 1 &amp;&amp; y &lt; 1000)));

First of all I removed the initial value of `lineVector` as it is unnecessary to initialize it in this case (you needed to do it because of it being present in your while condition).

I initialized `x` and `y` to -1 (Any number not in our range would work) in order to make sure the do-while condition is fulfilled until proper values are offered for both of the numbers.

**Function to check binary values**

Create a function to check if string values are binary.

    public static boolean isBinary(String s) {
        for(int i = 0; i &lt; s.length(); ++i) {
            char c = s.charAt(i);
            if(c != &#39;0&#39; &amp;&amp; c != &#39;1&#39;)
                return false;
        }
        return true;
    }

**Receive binaries**

    String[] binaries = new String[x];
    
    System.out.println(&quot;Enter binaries with length &quot; + y + &quot; :&quot;);
    
    //Get binaries
    for(int i = 0; i &lt; x; ++i) {
        binaries[i] = scanner.nextLine();
    
        while(!isBinary(binaries[i]) || binaries[i].length() != y) {
            System.out.println(&quot;Invalid binary value. Re-enter new value:&quot;);
            binaries[i] = scanner.nextLine();
        }
    }

Receive binary values and continue asking if invalid.

**Filling the 2D array**

    int[][] field = new int[x][y];

    for(int i = 0; i &lt; x; ++i) {
        System.out.println();
        for(int j = 0; j &lt; y; ++j) {
            char c = binaries[i].charAt(j);
            if(c == &#39;0&#39;)
                field[i][j] = 0;
            else
                field[i][j] = 1;

            System.out.print(field[i][j] + &quot; &quot;);
        }
    }

`Integer.parseInt` is not necessary here as there are only two possible values (0 and 1)

 

</details>



huangapple
  • 本文由 发表于 2020年7月25日 19:29:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63087796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定