Calling void methods from main method, cannot pass arguments within void methods - java

my teacher asked us to create an additive prime program for my computer science class. I have created all my void methods, and believe to have all the math logic figured out. However, when I try to pass arguments into the instances of my methods within my main method, It gives me an error saying:
it can not find the variable in this case variable 'x'
package additiveprimes;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author talarik048
*/
public class AdditivePrimes {
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public void userInput(String x){
Scanner sc = new Scanner(System.in);
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
}
public void isPrime(String x){
this.userInput(x);
boolean prime = true;
int y = Integer.parseInt(x);
for(int i = 0; i < y; i++){
if(y % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is prime...");
} else {
System.out.println("Your number is not prime...");
}
}
}
public void numArray(String x){
this.userInput(x);
String[] strArray = x.split("\\s+");
boolean prime = true;
int[] numbArray = new int[strArray.length];
for(int j = 0; j < strArray.length; j++){
try{
numbArray[j] = Integer.parseInt(strArray[j]);
} catch(NumberFormatException e){
System.out.println("ERROR");
}
for(int i = 0; i < numbArray.length; i++){
int sum = (Arrays.stream(numbArray).sum());
if(sum % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is an additive prime...");
} else {
System.out.println("Your number is not an additive prime...");
}
}
}
}
}

I think you wanted to RETURN a value from userInput:
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(Exception e){// see OH GOD SPIDERS comment
System.out.println("Error, try again: ");
x = sc.nextLine();//this is not a good way for a retry
}
return x;
}
Alternatively you could make x a field.

Your methods accept a string as an argument, but you have not passed any. You need to initialize x in main.
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x= "55";
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
Note
Although the above code fixes your current issue. It doesn't seem to be the correct way to use this class. You should probably be calling .userInput() method and getting the userInput then passing it to your other methods.
You could probably change your overall class to
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
return x;
}

You have not defined x as anything before using it. Try defining x. In this case since your arguments are strings, I recommend...
String x = new String();

Related

Is there any way of making this method run more than twice

I was asked to write a simple calculator that could run many times as long as the user inputs 'yes' when asked "would you like to perform another operation".
so I did it using a separate method that would be used in a loop in the main method, the problem is it wont run more than twice if the answer is yes
import java.util.Scanner;
public class Calc2 {
// method to be called
static String calcmethod() {
#SuppressWarnings("resource")
Scanner Operation = new Scanner(System.in);
System.out.println("choose operation to perform");
float x, y, sum, sub, mul, div;
String g;
g = Operation.nextLine();
if (g.equals("addition")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sum = x + y;
System.out.print(sum + "\n");
} else if (g.equals("subtraction")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sub = x - y;
System.out.print(sub);
} else if (g.equals("multiplication")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
mul = x * y;
System.out.print(mul);
} else if (g.equals("division")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
div = x / y;
System.out.print(div);
} else {
System.out.println("invalid input \n");
}
System.out.println("would you like to peform another operation \n");
Scanner Flow = new Scanner(System.in);
String w;
w = Flow.nextLine();
return w;
}
public static void main(String[] args) {
String z = calcmethod();
if (z.equals("yes")) {
calcmethod();
} else {
System.out.println("end of program");
}
}
}
Use do-while loop as shown in below example:
public static void main(String[] args) {
String z = "";
do {
z = calcmethod();
} while(z.equals("yes"));
System.out.println("end of program");
}

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

How do I use the interface for this number reverse program, instead of using the program entry itself? (JAVA)

I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}

How to parse int from String

I have to keep inputting x and y coordinates, until the user inputs "stop". However, I don't understand how to parse the input from String to int, as whenever I do, I get back errors.
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
System.out.println("Enter x:");
String x = kb.nextLine();
if (x.equals("stop")) {
System.out.println("Stop");
break;
}
System.out.println("Enter y:");
String y = kb.nextLine();
if (y.equals("stop")) {
System.out.println("Stop"); }
break;
}
}
}
}
To Parse integer from String you can use this code snippet.
try{
int xx = Integer.parseInt(x);
int yy = Integer.parseInt(y);
//Do whatever want
}catch(NumberFormatException e){
System.out.println("Error please input integer.");
}
Nice way to do this in my opinion is to always read the input as a string and then test if it can be converted to an integer.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
String input;
int x = 0;
int y = 0;
System.out.println("Enter x:");
input = kb.nextLine();
if (input.equalsIgnoreCase("STOP")) {
System.out.println("Stop");
break;
}
try {
x = Integer.parseInt(input);
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("No valid number");
}
}
}
}
With
String variablename = Integer.toString(x);

unexpected results - can please some one point the mistake

after spending number of hours and trying different things, i can't figure out what is wrong with my code, it's a simple program : `
public class AssignGrades {
private int ntotal=0;
private int []y;
//constructor to initialize class instances
AssignGrades(int t)
{
ntotal = t;
//y = num1;
}
AssignGrades( int []num1)
{
y=num1;
for (int i=0;i<y.length;i++)
y[i] = num1[i];
}
//method to sort grades int []num1
void setGrades()
{
int [] y = new int[ntotal];
for (int i=0;i<y.length;i++)
{
//assign grades
if
(y[i]<80){
System.out.println("grade is A" +y[i]);}
else if (y[i]<70)
System.out.println("grade is B" +y[i]);
else if (y[i]<60)
System.out.println("grade is c" +y[i]);
else
System.out.println("FAIL" +y[i]);
}
}
//show student grades - to print array[] values
void showGrades()
{
for (int u: y)
System.out.println(u);
}
}`
my client program
`import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int t=0;
System.out.println("enter no of students" );
Scanner input = new Scanner(System.in);
{
t=input.nextInt();
// input.close();
}
int [] num1 = new int[t];
System.out.println("enter grades");
Scanner input1 = new Scanner(System.in);
for (int i=0;i<num1.length;i++)
{
num1[i]=input1.nextInt();
}
input1.close();
AssignGrades ag = new AssignGrades(t);
AssignGrades ag1 = new AssignGrades( num1);
ag.setGrades();
ag1.showGrades();
}
}
output is:
enter no of students
2
enter grades
78
98
grade is A0
grade is A0
78
98
Question: now in the output 'A' and '0' -> where the problem is, it looks like array is not initialized, all the values appear to be zero: whereas when I print them separately, they are initialized.?!
Please let me know if more clarification is required. thanks
You have a local variable called y and a class variable with the same name y. That seems to be the problem. You are using the local y but you meant to use the class y, I think.
OK, your code had lots of problems. Here is the fixed version.
public class AssignGrades {
private int[] y;
public AssignGrades(int[] num1) {
y = num1;
}
// method to set grades
void setGrades() {
for (int i = 0; i < y.length; i++)
{
// assign grades
if (y[i] < 50)
System.out.println("FAIL" + y[i]);
else if (y[i] < 60)
System.out.println("grade is C" + y[i]);
else if (y[i] < 70)
System.out.println("grade is B" + y[i]);
else if (y[i] < 80) {
System.out.println("grade is A" + y[i]);
}
}
}
// method to show student grades
void showGrades() {
for (int u : y){
System.out.println(u);
}
}
}
import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
int t = 0;
System.out.println("enter no of students");
Scanner input = new Scanner(System.in);
t = input.nextInt();
int[] num1 = new int[t];
System.out.println("enter grades");
for (int i = 0; i < num1.length; i++) {
num1[i] = input.nextInt();
}
input.close();
AssignGrades ag = new AssignGrades(num1);
ag.setGrades();
ag.showGrades();
}
}

Categories