标签:输出 获取 bsp rand str ring 要求 个数 oid
题目1: 编程实现,现在有如下的一个数组:
int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为。
int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5};
1 public class Exer { 2 3 public static int[] getNewArr(int[] arr){ 4 int count=0; 5 6 for(int i : arr) { 7 if(i != 0) { 8 count++; 9 } 10 } 11 12 int j = 0; 13 int[] newArr=new int[count]; 14 for(int i =0;i<arr.length;i++) { 15 if(arr[i] != 0) { 16 newArr[j]=arr[i]; 17 j++; 18 } 19 } 20 21 return newArr; 22 } 23 24 public static void main(String args[]) { 25 int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; 26 27 28 int[] newArr = getNewArr(oldArr); 29 System.out.print("int newArr[]={"); 30 for(int i=0;i<newArr.length;i++) { 31 if(i==newArr.length-1) { 32 System.out.print(newArr[i] + "};"); 33 }else { 34 System.out.print(newArr[i] + ","); 35 } 36 } 37 } 38 }
题目2:编程实现,要求程序输出某两个整数之间的随机整数。
1 import java.util.Random; 2 import java.util.Scanner; 3 4 public class exer1 { 5 6 public static void getRandomNumBetweenXAndY(int x,int y) { 7 Random rand = new Random(); 8 //获取两个数之间的绝对值 9 int abs = Math.abs(x-y); 10 11 if(abs <= 1) { 12 System.out.println(x + "和" + y + "之间已经没有随机整数了"); 13 }else { 14 //获取两个数之间的随机数,选择最小的数作为底数,然后加上两个值之间的绝对值的随机整数 15 int randomNum = x > y ? rand.nextInt(abs) + y : rand.nextInt(abs) + x; 16 System.out.println(x + "和" + y + "之间的随机数是:" + randomNum); 17 } 18 } 19 public static void main(String args[]) { 20 //从控制台获取x和y的值 21 Scanner scanner = new Scanner(System.in); 22 System.out.println("请输入x的值"); 23 int x = scanner.nextInt(); 24 System.out.println("请输入y的值"); 25 int y = scanner.nextInt(); 26 //调用方法获取x和y之间的随机整数 27 getRandomNumBetweenXAndY(x,y); 28 } 29 }
标签:输出 获取 bsp rand str ring 要求 个数 oid
原文地址:https://www.cnblogs.com/xzhm/p/12237062.html