Whats wrong with this method? Why won't it pass test case? - java

This code is supposed to count from an inputted parameter from a user, pass it to a function and it counts it down to one. I believe the program acts as it should, the problem is that it doesn't pass Mooc.fi's tests
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = Integer.valueOf(scanner.nextLine());
printFromNumbertoOne(number);
}
public static void printFromNumbertoOne(int number) {
for (int i = number; i > 0; i--) {
System.out.println(i);
}
The error I'm receiving is:
Method printFromNumberToOne(int) of class FromParameterToOne missing
What am I missing? And is there a way to check the test cases? Mooc.fi seems like it's very picky on what it takes for answers.
Thanks!

CAMELCASE of the method!
After beating my head against this problem all day it came to me after taking a break.
It should be printFromNumberToOne

Related

Is there a way to only get the value from an input method to another method without repeating the whole process again in java?

I really want to know if there is a way to only get the value from the method to an another method. Because in the main method the first method is already call out while the the second needed the value of the input from the first method.
//Main method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int an = 0;
an = first_method(an);
second_method();
}
//First Method
static int first_Method (int num) {
Scanner reader = new Scanner(System.in);
boolean done = false;
int num = 0;
while(!done) {
try {
System.out.print("Enter a Number: \t\t");
num = reader.nextInt();
done = true;
}
catch (InputMismatchException e) {
String s = reader.nextLine();
System.out.println("Invalid a number: " + s);
}
}
return num;
}
//Second Method
static void second_method()
{
int anum = 0;
anum = first_method(anum);
System.out.println(anum);
}
P.S. I know that my question have similar question from others in here but so far from what I have search there is none that solve my problem with a mismatch exception so if there is any same problem as me and already question in here then you can link it. Thanks
Sure. Its called a 'parameter':
static void secondMethod(int v) {
System.out.println(v);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int an = firstMethod(an);
secondMethod(an);
}
Here, you let firstMethod run, it produces a result (it's what you return). You then pass that result to secondMethod. Parameters are like local variables, except they are initialized to a value that the code that invokes your method determines. Here, the secondMethod method has a local variable named v, and its value starts out as whatever the code that calls secondMethod wants it to be. Here, we want it to be whatever firstMethod returned, thus letting us pass something firstMethod calculated, to secondMethod to work on.
Here, you let firstMethod run, it produces a result (it's what you return). You then pass that result to secondMethod. Parameters are like local variables, except they are initialized to a value that the code that invokes your method determines. Here, the secondMethod method has a local variable named v, and its value starts out as whatever the code that calls secondMethod wants it to be. Here, we want it to be whatever firstMethod returned, thus letting us pass something firstMethod calculated, to secondMethod to work on.

"GridWorld" for ThinkJava Exercise 5.1

Newbie completeing thinkJava book and trying to figure out one of the answers to the exercises. It calls for me to download the "GridWorld" files and complete the following steps:
Write a method named moveBug that takes a bug as a
parameter and invokes move. Test your method by calling it from main.
Modify moveBug so that it invokes canMove and moves the bug only if
it can.
Modify moveBug so that it takes an integer, n, as a parameter, and
moves the bug n times (if it can).
Modify moveBug so that if the bug can’t move, it invokes turn instead.
I am stuck on number 3, I can not figure out how to pass n into the "move() method"
-Please Help I am a newbie
My Code:
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;
public class BugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Bug redBug = new Bug();
world.add(redBug);
world.add(new Rock());
world.show();
moveBug(redBug,5);
System.out.println(redBug.getLocation());
}
public static void moveBug(Bug aBug, int n){
if(aBug.canMove() == true){
aBug.move();
} else {
aBug.turn();
}
}
}
You mean you're stuck on number 3:
Modify moveBug so that it takes an integer, n, as a parameter, and moves the bug n times (if it can).
This means write a loop, looping n times, calling move() once per iteration, if canMove() returns true.
BTW: if (canMove() == true) {...} is the long way to say if (canMove()) {...}.
And fix the indentation of the if statement.
Thanks for pointing me #Andreas
My Solution that worked:
public static void moveBug(Bug aBug, int n){
for(int i = 0; i < n; i++){
if(aBug.canMove())
{
aBug.move();
} else {
aBug.turn();
}
}
}

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Why does Jcreator show iIlegal start of expression?

I am new at programming and currently in our classes we are learning java. I am trying to create a routine in which I need to use String variables only. Below it is the code in which I am working with:
public static void main(String[] args) throws java.io.IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System. in ));
PrintStream out = System.out;
String hair.equals("damagedHair");
cutHair(marvin);
cleanHair(michelle);
for (int i = 0; i < 2; i++) {
static void cutHair(String marvin) {
String cabello;
marvin.equals(hair);
if (marvin.equals("damagedHair")) {
cabello.equals("newHaircut");
result(hair);
}
static void cleanHair(String michelle) {
String hair;
michelle.equals(hair);
if (michelle.equals(newHaircut)) {
hair.equals("putShampooAndConditioner");
result(hair);
}
static void result(String pHair) {;
PrintStream out = System.out;
out.println("=============");
out.println(pHair);
out.println("=============");
}
}
Jcreator is giving me an error that says Illegal start of expression and also java 50 error ';' expected.
I am not sure why is this coming up and I am a little confused as to whether I am doing something I am not supposed to and how to correct it. Sorry about the double posting, this is the right message. Need some help from you guys to figure this out.
Thanks in advanced!
This is in your main:
for(int i=0; i<2; i++)
{
static void cutHair(String marvin)
{
String cabello;
marvin.equals(hair);
if(marvin.equals("damagedHair"))
{
cabello.equals("newHaircut");
result(hair);
}
}
You cannot define methods inside of main. Also, hair is not in scope here, ie it's in your main, not your method. Additionally, you're constantly only declaring variables, and then using them without them ever having been initialized. For example, in the above method, you have:
cabello.equals("newHairCut")
but cabello was never initialized, this should give you a might not have been initialized warning. Or earlier in your code, you have:
String hair.equals("damagedHair");
Again, this doesn't make any sense. You just declared hair here, you cannot call methods on it until you initialize it. I suggest that you review some tutorials.

JUnit test for console input and output

I have only one method main. How to check System.out.println() and replace Scanner to input values automatically using JUnit?
P.S. Please, provide some solutions...
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int res = 0;
int k = 0;
int num = arr[i];
/*.....*/
System.out.println(num);
}
}
Ideally, extract the awkward dependencies so that you can test without them. Change main to simply:
public static void main(String[] args) {
doWork(new Scanner(System.in), System.out);
}
// TODO: Rename to something meaningful
public static void doWork(Scanner input, PrintStream output) {
// Remainder of code
}
(Consider using a Writer instead of a PrintStream for output.)
Then you don't really need to unit test main - but you can test doWork using a Scanner based on a StringReader, and output based on a StringWriter, providing whatever input you want and checking the output.
I faced a similar issue and this is what I ended up doing.
First off, I'd suggest doing as #Jon-Skeet suggests and instead of using the main(String[]) method of the class, create a separate method.
Then you can have that method take in an InputStream as a parameter and then create a Scanner object within the method that uses the passed InputStream as its source. That way you can pass any InputStream, such as System.in, to the method when it's called (elaboration below).
package my.package;
import ...;
public class MyClass
{
public static void myMethod(InputStream inputStream)
{
Scanner inputScanner = new Scanner(inputStream);
// Do stuff with the Scanner such as...
String input = inputScanner.nextLine();
System.out.println("You inputted " + input);
}
}
Now, in your production source code you can call myMethod and pass it System.in as an argument as such, myMethod(System.in);
And then in your unit tests, you can create mock input values via a ByteArrayInputStream:
package my.package;
import ...;
public class MyClassTest
{
#Test
void testMyMethod()
{
// Simulates a user inputting the string "Mock input" and hitting enter
assertDoesNotThrow(myMethod(new ByteArrayInputStream("Mock input\n".getBytes())));
}
}
And voila, you now have a way to pass your method mock input as well as it being more modular overall.
I just want to point out without getting too much into it, that when working with System.in, one needs to be careful about closing it and in unit tests when working with input streams, one needs to be careful about reusing a reference to the same InputStream as its state can persist across uses.

Categories