我目前开始学习使用Java编程。我试图在Java中编写出题目中的序列作为输出,但我卡住了!我正在尝试使用for函数进行实验,欢迎任何帮助;)
如何在Java中输出序列1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 ...? [关闭]
原标题:
It s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
最佳回答
System.out.println("1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0");
但说真的,各位,这只是一个未经测试的初步尝试:
for(int i=1; i<100; i++){
System.out.print("1 ");
for(int j=0; j<i; j++){
System.out.print("0 ");
}
}
如果你正在寻找如何入门的基本信息,Google就是你的好朋友。例如,尝试在Google上搜索“for loop java”,你将得到很多好的示例。另外,在任何语言中学习基本事物,搜索“
问题回答
为什么两个循环?
(从C#转换,原谅任何语法错误)
String s = "1 ";
for (int i = 0; i < 5; ++i)
{
s = s + "0 ";
System.out.print(s);
}
自我批评
- two for loops (like Michael Haren s solution) would negate the string copying
- a StringBuffer/StringBuilder would negate the string copying
你可以将数字“10”存储在一个变量中,在循环中打印该数字,将其乘以10(这会在其小数表示中附加一个零),然后重复以上步骤。
for (int i = 2; i < 64; i <<= 1)
//System.out.print(Integer.toString(i, 2));
System.out.print(Integer.toString(i, 2).replaceAll("[01]", "$0 "));
This is not really a question of fors but rather of very rudimentary algorithmic thinking. You have a sequence that consists of a "1", and then something else that grows over time", another "1", another something, etc. You can think of these as two different series that are interleaved.
因此,总体结构应该是这样的:
while(... infinity?)
{
System.out.print("1");
doSomething();
}
现在,某些东西显然与外循环的迭代次数(“阶段”)或1的计数相关,因此您需要类似以下的东西:
int stage=0;
while(...infinity?)
{
++stage;
System.out.print("1");
for(int i=0; i<stage; ++i) System.out.print("0");
}
如果您知道需要多少个周期,请使用for循环而不是while,并通过它增加阶段。
Or did your teacher ask you to? Two nested for loops will do the trick.
或者用另一种语言(Ruby)的另一种方式:
4.times {|n| print 10**(n+1)}
f或者 (huòzhě) (int i = 1; i < 100000;)
{
i = i * 10;
System.out.print(i);
}
或者 (huòzhě)
int i = 1;
while (i < 100000)
{
i = i * 10;
System.out.print(i);
}
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding