所以我试图找到总和为素数的数字对。因此,用户将仅输入4个条目。我的问题是如何将输入方法中的变量num1 num2 num3 num4共享到另一个名为sumPair的方法。但我得到一个名为Required:Variable found:value
的错误import java.util.Scanner;
public class PrimePair
{
public static int num1, num2, num3, num4;
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
input(num1,num2,num3,num4);
}
public static void input (int num1, int num2, int num3, int num4)
{
num1 = 0;
{
System.out.print("Enter a positive integer: ");
num1 = input.nextInt();
if(num1 > 0)
{
System.out.println("Thank you.");
}
else
while(num1==0 || num1 < 0)
{
System.out.print("Enter a positive integer: ");
num1 = input.nextInt();
}
}
num2 = 0;
{
System.out.print("Enter a positive integer: ");
num2 = input.nextInt();
if(num2 > 0)
{
System.out.println("Thank you.");
}
while(num2 == 0 || num2 < 0)
{
System.out.print("Enter a positive integer: ");
num2 = input.nextInt();
}
}
num3 = 0;
{
System.out.print("Enter a positive integer: ");
num3 = input.nextInt();
if(num3 > 0)
{
System.out.println("Thank you.");
}
while(num3 ==0 || num3 < 0)
{
System.out.print("Enter a positive integer: ");
num3 = input.nextInt();
}
}
num4 = 0;
{
System.out.print("Enter a positive integer: ");
num4 = input.nextInt();
if(num4 > 0)
{
System.out.println("Thank you.");
}
while(num4 == 0 || num4 < 0)
{
System.out.print("Enter a positive integer: ");
num4 = input.nextInt();
}
}
}
public static int sumPair(int num1, int num2)
{
num1 + num2 = sum1;
return sum1;
}
}
答案 0 :(得分:1)
您像任何其他方法一样调用void
方法,只是它不返回值,因此您无法将结果分配给任何内容。在你的情况下:
public static void main(String args[])
{
int in = input();
int[] comparisons = ...;
findThePairs(comparisons, in);
}
阅读Java教程。
答案 1 :(得分:0)
请注意,我将您的输入方法放在您的类中,您编写的每个代码都应该在类
中import java.util.Scanner;
public class PrimePair
{
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int in = input();
???????//calling the void method
int exampleArray[] = {3,4,6};
int someNumber = 1;
findThePairs(exampleArray, someNumber);
// For void you don't have return value so variable isn't needed as with other methods which return some value
}
public static void findThePairs(int inputArray[], int inputNumber)
{
for (int i = 0; i < inputArray.length; i++)
{
for (int j = i+1; j < inputArray.length; j++)
{
if(inputArray[i]+inputArray[j] == inputNumber)
{
System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
}
}
}
public static int input ()
{
int count = 0;
int num = 0;
while (count < 4)
{
System.out.print("Enter a positive integer: ");
num = input.nextInt();
{
if(num > 0)
{
System.out.println("Thank you.");
count++;
}
}
}
return num;
}// End of input method
}// End of class