对不起,也许我没有解释清楚。这是我的实践
输入正整数。如果输入不是肯定的,则您的算法应输出错误消息并重新提示用户输入。此过程应继续循环,直到输入有效。然后,您的算法应输出输入是否为偶数和3的倍数。注意您的解决方案必须适当使用子模块。
我必须创建一个从用户输入获取正数的方法,并且我需要从此ArrayList显示偶数和3的多个。我已经为此编写了代码,但我一直在努力使用另一个子模块来显示这个ArrayList。
import java.util.ArrayList;
import java.util.*;
public class Array {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list;
list = new ArrayList<Integer>();
int number = -1;
printList(list, number );
System.out.println("Enter number. Enter 0 to end.");
while (true)
{
System.out.print(" ");
number = sc.nextInt();
while( number < 0)
{
System.out.print("Enter your next positive integer, or 0 to end: ");
number = sc.nextInt();
}
if (number == 0)
break;
list.add(number);
}
}
public static void printList (ArrayList<Integer> list, int number)
{
for(int i = 0;i <= number.size(); i++)
{
if(i % 2 ==0 && i % 3 ==0)
{
System.out.println(list(i));
}
}
}
}
答案 0 :(得分:1)
好的,我得到你的问题,看起来你无法打印列表,你应该修改一下你的代码
你只需要在while循环后粘贴printList()。
while (true)
{
System.out.print(" ");
number = sc.nextInt();
while( number < 0)
{
System.out.print("Enter your next positive integer, or 0 to end: ");
number = sc.nextInt();
}
if (number == 0)
break;
list.add(number);
}
printList(list);
并且你的printlist方法不正确,它应该是这样的
public void printlist(List<Integer> numberList){
for(int i = 0;i <= numberList.size(); i++)
{
if(i % 2 ==0 && i % 3 ==0)
{
System.out.println(numberList.get(i));
}
}
}
希望这有帮助! 祝你好运!
答案 1 :(得分:1)
请参阅以下代码帮助
public class Array {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list;
list = new ArrayList<Integer>();
int number = -1;
System.out.println("Enter number. Enter 0 to end.");
while (true) {
System.out.print(" ");
number = sc.nextInt();
while (number < 0) {
System.out.print("Enter your next positive integer, or 0 to end: ");
number = sc.nextInt();
}
if (number == 0) {
sc.close();
break;
}
list.add(number);
printList(list, number); // Moved the print here.
}
}
public static void printList(ArrayList<Integer> list, int number) {
for (int i = 0; i <= list.size(); i++) { // You have to get size on
// list.
if (i % 2 == 0 && i % 3 == 0) { // Are you planning to check the
// index or the content in the list
// ?
System.out.println(list.get(i)); // Get the number from list
}
}
}
}
答案 2 :(得分:0)
我认为你正在寻找一个像这样的程序吗?
public class Array {
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
int number;
do {
System.out.print("Enter a positive integer or 0 to end: ");
number = sc.nextInt();
if (number > 0) { list.add(number); }
} while (number != 0);
for (int i = 0; i < list.size(); i++) {
int number = list.get(i);
if (number % 2 == 0 && number % 3 == 0) {
System.out.println(number);
}
}
}
}
由于IndexOutOfBoundException
讨论,请考虑以更安全可读的方式打印您的数字(如果您使用的是Java 8):
list.stream().filter(num -> num % 2 == 0)
.filter(num -> num % 3 == 0)
.forEach(System.out::println);