我正在尝试为一个类编写一些基本代码,该类要求我选择3个随机数,然后询问用户输入并查看这些随机数是否以不同方式匹配。无论如何,我特别需要使用for循环来生成这3个数字,但它只生成一个。请帮忙。
编辑:我删除了有问题的行,但现在看来我连接错了,我的firstNumber,secondNumber和所有这些变量都是空白的?我不确定是什么导致了这个
import java.util.Scanner;
public class Lotteryv2
{
public static void main(String[] args)
{
//Generate a random number
String numberString = "";
for(int i = 0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
numberString += lotteryNumberDigit;
}
System.out.println(numberString);
//extracting number string
String firstNumber = numberString.substring(0,0);
String secondNumber = numberString.substring(1,1);
String thirdNumber = numberString.substring(2,2);
String firstWin = firstNumber + secondNumber;
String secondWin = secondNumber + thirdNumber;
String allWin = firstNumber + secondNumber + thirdNumber;
// user guess
Scanner input = new Scanner (System.in);
System.out.println("Please enter three numbers (e.g 123): ");
String guess = input.next();
if (guess.substring(0,2).equals(firstWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed the first two numbers correctly!");
}
else if(guess.substring(1,3).equals(secondWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed the last two numbers correctly!");
}
else if(guess.equals(allWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed all three numbers correctly!");
}
else
{
System.out.println("Winner! " + allWin);
System.out.println("Sorry, you did not win");
}
//extracting three guess digits
}
}
答案 0 :(得分:3)
你的循环确实进行了三次。但是,可见结果与仅执行一次迭代的结果相同,因为第二次迭代会对第一次迭代的结果进行写入,而第三次迭代会在您对它们执行任何操作之前覆盖第二次迭代的结果。
这是有问题的一行:
app/views/home/index.html.erb:252: syntax error, unexpected ':', expecting ')'
app/views/home/index.html.erb:288: syntax error, unexpected keyword_class, expecting ')'
删除后,您的代码将打印一个三位数的数字字符串(可能带有前导零)。
提取单个数字的代码也需要更改:由于numberString = Integer.toString(lotteryNumberDigit);
独占,您需要向其添加endIndex
:
1
此外,您需要检查最终用户输入的值是否至少为三位数。否则,当从String firstNumber = numberString.substring(0, 1);
String secondNumber = numberString.substring(1, 2);
String thirdNumber = numberString.substring(2, 3);
变量中提取数字时,您将获得异常。
答案 1 :(得分:1)
您将数字的值分配给单个String变量,从而在每次迭代中覆盖它。您可以将其更改为:
You can use this utility function from itertools, since file handle
is iterable.
def head(n, iterable):
from itertools import islice
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
# to get first 20 rows
head(20,open('file.csv'))