3

DISCLAIMER: This is a homework assignment

Goal of the program is: ask a sentence and then: - convert upper to lowercase (without using .toLowercase() ) - remove all characters that are not a-z, A-Z and 0-9 - print new sentence - ... something more BUT not important for.

Ok, so what I did.

  • I converted my String (sentence) to a char array.
  • I created a for loop to loop through all chars in my array
  • If a char is a uppercase I converted it to a lowercase using ASCII

The problem I experience is: - It looks like I change the char C but it's NOT stored as a lowercase in my array? - How do I detect the non-allowed characters, and delete this from my array?

My code:

import java.util.Scanner;

public class sentence {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String zin = ""; 

    System.out.print("Voer een zin in: ");
    if (scanner.hasNextLine())                        
        zin = scanner.nextLine().trim();

    if (zin.equals("")) {
        System.out.print("Geen Invoer!");
        System.exit(0);
    }

    char[] zinArray = zin.toCharArray(); 
    for (int i = 0; i < zinArray.length; i++) { 
        char c = zinArray[i]; 
        if (c >= 'A' && c <= 'Z') {
        c = (char)(c + 32);
        } else if (c >= 58 && c <= 64) {

        } else if (c >= 91 && c <= 96) {

        } else if (c  123 && c <= 126) {
      }

    }
    }
}

Can anyone point me in the right direction?

Thanks :)

4

3 回答 3

5

考虑以下行:

char c = zinArray[i];

分配复制值(或引用,如果是类实例)。因此,您在 处创建了角色的副本zinArray[i]。这意味着更改变量c的值不会更改存储在zinArray[i]. 您必须对数组项执行更改,如下所示:

zinArray[i] = (char)(c + 32);
于 2013-09-10T10:39:25.000 回答
1

这是答案代码:

问题是您从未将值分配回数组,而不是在您想要小写字母时,而不是取消符号

import java.util.Scanner;

public class sentence {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String zin = ""; 

    System.out.print("Voer een zin in: ");
    if (scanner.hasNextLine())                        
        zin = scanner.nextLine().trim();

    if (zin.equals("")) {
        System.out.print("Geen Invoer!");
        System.exit(0);
    }

    char[] zinArray = zin.toCharArray(); 

    for (int i = 0; i < zinArray.length; i++)
    { 
        char c = zinArray[i];  // ASSINGING A LOWER CASE
        if (c >= 'A' && c <= 'Z') 
        {
           zinArray[i] = (char)(c + 32);
        } 
          else if ((c >= 58 && c <= 64) ||
                   (c >= 91 && c <= 96) ||
                   (c  123 && c <= 126))
        {
            zinArray[i] = ' ';// REMOVING SIGNS
        }
      }
    }
}
于 2013-09-10T10:47:03.723 回答
1

将代码更改为:

c = (char)(c + 32);
    zinArray[i]=c;

基本上你正在将大写字母转换为小写字母。那部分是正确的,但您没有将小写字母存储回数组,这就是它没有显示在输出中的原因。

于 2013-09-10T10:42:00.853 回答