2014-10-07 37 views
-3

问题上的措辞如下:找到最高和最低的位数在任何给定长度的只数字符串

“要求用户输入一系列一无所有的个位数的将它们分开的程序应该显示字符串中的最高和最低位数字,并且程序应该显示一个只包含偶数位和一个只包含奇数位的字符串的字符串。“

显然,我需要将输入字符串(我们称之为numberInput)以某种方式转换或解析为最高和最低整数,以及它对于所有奇数和偶数整数。

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    String numberInput; // The variable of the string 
    System.out.println("Enter any number of positive digits, not separated by anything: "); // prompt user 
    numberInput = scan.next(); // read in the string 

    int phraseLength = numberInput.length(); // get length of input string 
    int middleIndex = phraseLength/2; // find the middle index of input string 

    String highestDigits, lowestDigits; //?? just guessing here 
    int max, min; //?? made variables for highest value integer and lowest value integer 
} 
+2

究竟什么是你的问题? – EvilTeach 2014-10-07 02:17:44

+0

我需要找到String numberInput中的最高位和最低位。例如,如果用户输入1237827,我需要输出8(最高位)和1(最低位)。我还需要创建一个字符串,其中包含奇数字符串numberInput和一个包含偶数字符串numberInput的字符串。再次,如果用户输入1237827,我需要输出一个包含'1377'的字符串和一个包含'282'的字符串。 – magnum482 2014-10-07 02:28:34

+2

向我们展示您的尝试。尝试将字符串转换为“int”或“char”数组。 – user1803551 2014-10-07 02:43:41

回答

0

我觉得你在找什么是循环和text.charAt(index)。尝试在java中查找while/for循环的语法,并使用它们循环遍历字符串,将字符串中的每个字符转换为一个int并将它们进行比较。您可以跟踪当前的min/max并在必要时更新它们,检查字符串中的每个字符。

一个例子是

int max = Integer.MIN_VALUE; 
int min = Integer.MAX_VALUE; 
for (counter=0;counter<phraselength;counter++) { 
    int this_int = (int)numberInput.charAt(counter); 
    if (this_int < min) { 
     min = this_int; 
    } 
    if (this_int > max) { 
     max = this_int; 
    } 
} 
0

由于这是一个可以由小研发来解决一个明确的任务,所以我告诉我下投票这样

Java 8

代码

String s = "1237827"; 
    String[] sp = s.split(""); 

    int max = Arrays.stream(sp) 
      .mapToInt(st -> Integer.parseInt(st)).max().getAsInt(); 

    int min = Arrays.stream(sp) 
      .mapToInt(st -> Integer.parseInt(st)).min().getAsInt(); 

    System.out.println("The maximum number is " + max); 
    System.out.println("The minmum number is " + min); 

    System.out.print("The even numbers list is:"); 
    Arrays.stream(sp) 
      .mapToInt(st -> Integer.parseInt(st)) 
      .filter(i -> i % 2 == 0) 
      .forEach(i -> System.out.print(i + " ")); 
    System.out.println(""); 
    System.out.print("The odd numbers list is:"); 
    Arrays.stream(sp) 
      .mapToInt(st -> Integer.parseInt(st)) 
      .filter(i -> i % 2 != 0) 
      .forEach(i -> System.out.print(i + " ")); 
    IntSummaryStatistics stats = Arrays.stream(sp) 
      .mapToInt(st -> Integer.parseInt(st)) 
      .summaryStatistics(); 
    System.out.println(stats); 

输出

The maximum number is 8 
The minmum number is 1 
The even numbers list is:2 8 2 
The odd numbers list is:1 3 7 7 
IntSummaryStatistics{count=7, sum=30, min=1, average=4.285714, max=8} 
相关问题