完整代码为:
public class Main {
public static void main(String[] args) {
int index = 1
int[] redBalls = new int[6]
Random random = new Random()
boolean getMoreRed = true
boolean getAgain
System.out.println("开始抽取红球!")
while (getMoreRed) {
getAgain = false
int red = random.nextInt(36) + 1
System.out.print("本次抽取到的红球为:[" + red + "]!")
for (int i = 0i <indexi++) {
if (redBalls[i] == red) {
System.out.print("重复抽取,将重新抽取红球")
getAgain = true
break
}
}
System.out.println("")
if (getAgain){
continue
}
redBalls[index - 1] = red
index++
getMoreRed = index <7
}
System.out.println("抽取到的红球为:")
Arrays.sort(redBalls)
for (int redBall : redBalls) {
System.out.print(redBall + " ")
}
System.out.println("\n\n开始抽取蓝球!")
System.out.println("本次抽取到的蓝球为:[" + (random.nextInt(16) + 1) + "]!")
}
}
运行结果:
普通抽取:
重复时抽取:
要制造那种效果只需要大约 30 行 Java 代码:
import javax.swing.*
import java.awt.*
import java.awt.geom.*
class RollingBall extends JPanel {
Ellipse2D.Float ball = new Ellipse2D.Float( -100, 100, 50, 50 )
public void paintComponent( Graphics g ) {
super.paintComponent( g )
Graphics2D g2 = ( Graphics2D ) g
// Draw the ball
g2.fill( ball )
// Draw the rotating ellipse by skewing the Device Space
double angdeg = // One rotation per ball's travelling over its perimeter
ball.x++ % ( Math.PI * ball.width ) / ( Math.PI * ball.width ) * 360
g2.rotate( Math.toRadians( angdeg ), ball.getCenterX( ), ball.getCenterY( ) )
g2.scale( .5, 1 )
g2.translate( ball.getCenterX( ), 0 )
g2.setColor( Color.gray )
g2.fill( ball )
}
public void roll( ) throws Exception {
while( true ) {
repaint( )
Thread.sleep( 8 )
}
}
public static void main( String[ ] args ) throws Exception {
JFrame f = new JFrame( )
RollingBall rb = new RollingBall( )
f.setSize( 999, 185 )
f.getContentPane( ).add( rb )
f.setVisible( true )
rb.roll( )
}
}
这是一个约瑟夫环问题,只不过是数到13时把球拿走,到剩下15个球为止.按照题意编写的Java程序如下
import java.util.ArrayListimport java.util.Collections
import java.util.List
public class AAA {
public static void main(String[] args) {
List<Integer> l2=new ArrayList<Integer>()//存放被拿出的红球的位置
List<Integer> l=new ArrayList<Integer>()//存放最初30个球的位置
for(int i=1i<=30i++){
l.add(i)
}
int point=0,number=1
while(l.size()>15){
if(number%13==0){
l2.add(l.get(point))
l.remove(point)
--point
}
++point
++number
if(point>l.size()-1){
point=0
}
}
System.out.println("被依次拿走的球的位置为"+l2.toString())
Collections.sort(l2)//对被依次拿走的球的位置排序
System.out.println("红球的位置为"+l2.toString())
}
}
运行结果
被依次拿走的球的位置为[13, 26, 9, 23, 7, 22, 8, 25, 12, 30, 18, 6, 29, 20, 15]
红球的位置为[6, 7, 8, 9, 12, 13, 15, 18, 20, 22, 23, 25, 26, 29, 30]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)