这道java题怎么用while语句做,详见问题补充,求大神帮忙!Write a program segment that reads a sequence of integers until a 0 is encountered. For each number read, output the number of times the number can be divided by 2 before you get
来源:学生作业帮助网 编辑:六六作业网 时间:2025/01/23 23:31:27
这道java题怎么用while语句做,详见问题补充,求大神帮忙!Write a program segment that reads a sequence of integers until a 0 is encountered. For each number read, output the number of times the number can be divided by 2 before you get
这道java题怎么用while语句做,详见问题补充,求大神帮忙!
Write a program segment that reads a sequence of integers until a 0 is encountered. For each number read, output the number of times the number can be divided by 2 before you get 0. For example, if the input is:
2
9
-7
4
-3
0
The code will read in all the integers, and produce the following output:
2
4
3
3
2
这道java题怎么用while语句做,详见问题补充,求大神帮忙!Write a program segment that reads a sequence of integers until a 0 is encountered. For each number read, output the number of times the number can be divided by 2 before you get
import java.util.Scanner;
public class TestClass {
public static void main(String[] args){
System.out.println("这是你的示例:");
System.out.println("2 9 -7 4 -3 0");
int[] array = {2,9,-7,4,-3,0}; // 你在知道上的示例
System.out.println("输出结果:");
for(int number : array){// 遍历数组里的每一个数字
// 你要求用while循环,不过这个应该不算的吧? 而且这个可以转换成while循环的
// OR (以下代码是等价的)
// for(int i = 0; i < array.length; ++i){
// int number = array[i];
int index = 0; // 被2整除次数的计数器
while(number != 0 && number / 2 != 0){ // 当遍历到0时中止循环
// 你要求用while循环
index ++;
number = number / 2;
}
System.out.print(index++ + " ");
}
System.out.println("\n_______________________");// 换行
//////////以下是输入后再处理:
Scanner scanner = new Scanner(System.in); // 可以进行输入操作
System.out.println("请输入一个数组,用空格分开,Enter键结束:");
String lineNumber = scanner.nextLine(); // 读取一行用户输入
String[] arrayString = lineNumber.split(" ");// 分隔空格
if(lineNumber.length() > 0){
for(String str : arrayString){
// OR (以下代码是等价的)
// for(int i = 0; i < arrayString; ++i){
// String str = array[i];
int index = 0; // 被2整除次数的计数器
int number = new Integer(str);
while(number != 0 && number / 2 != 0){ // 当遍历到0时中止循环
// 你要求用while循环
index ++;
number = number / 2;
}
System.out.print(index++ + " ");
}
}else{
System.out.println("空!");
}
}
}