Question

I have the following java-program, that creates a random walk starting at (0,0) and continuing until x or y is greater than abs(n).

First: I get an error, when I try closing the Scanner by inserting "reader.close(); " in line 28. It says "Unreachable code". How can I fix that?

Second: Is it possible to create a different colour for the StdDraw.point when it reaches a point on one of the edges "n+1" or "n-1" ?

1 import java.util.*; 3 public class RandomWalkf 4 5 public static void main(String args)I 6 Scanner readernew Scanner(System. in); System.out.print(Enter the size of grid: ); // Taking input of the size of the grid 10 do [ try int n = reader.nextInt(); if(n<= 0) { 12 13 // Saves integer entered as str 15 // Catches error if integer is negative System.out.println(n is not a positive integer. Please enter a positive integer (0 to terminate): ); 17 18 19 20 21 else if (n > 0) walk(n); System.out.printlnCnEnter the size of grid: ); // Makes sure the program catches strings as an error. Prints error message and clears Scanner catch (InputMismatchException e) f 23 24 25 26 27 System.out.println(Input is not an integer. Please enter a positive (0 to terminate): ; reader.nextLineO } while (true); reader.slse) ね28 29 30 31 public static void givePos(int X, int ) 32 //A function to print the position System.out, format(\nPosition-(Xd %d) ,X,Y); , 34

0 0
Add a comment Improve this question Transcribed image text
Answer #1
Answer First :

        You miss the else condtion in your while loop which should be execute when n = 0. 
        So when you are not using break statement for while loop then the code after while loop is unreachable.
        You should give a condition in loop after that program can be continue.
        I make this for you now reader.close() is reachable.
        
        // yout main method
        public static void main(String[] args) {

                Scanner reader = new Scanner(System.in);

                System.out.print("Enter the size of grid : ");

                do {
                        try {
                                int n = reader.nextInt();

                                if (n < 0) {
                                        System.out.println(
                                                        n + " is not a positive integer. Please enter a apositive integer (0 to terminate): ");
                                } else if (n > 0) {
                                        walk(n);
                                        System.out.println("\nEnter the size of grid: ");
                                } else {
                                        break;
                                }
                        } catch (InputMismatchException e) {
                                System.out.println("Input is not an integer. Please enter a positive (0 to terminate):");
                                reader.nextLine();
                        }
                } while (true);

                reader.close();
        }
        
Answer Second :
        For use color you can use different color for StdDraw.point()
        
        example : 
        
        StdDraw.setPenColor(StdDraw.BLUE);
        StdDraw.point(n+1, n-1);
        StdDraw.setPenColor(StdDraw.MAGENTA);
Add a comment
Know the answer?
Add Answer to:
I have the following java-program, that creates a random walk starting at (0,0) and continuing until...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation...

    I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation problem: at EvenOdd.main(EvenOdd.java:10) I am unable to find what I can do to fix this issue. Can you please assist? My code is below: import java.util.InputMismatchException; import java.util.Scanner; public class EvenOdd {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        System.out.println("Welcome to this Odd program!");        int userInput1 = input.nextInt();    }       public...

  • Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly...

    Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly below): //Create public class count public class Count {     public static void main(String args[])     {         int n = getInt("Please enter an integer value greater than or equal to 0");                System.out.println("Should count down to 1");         countDown(n);                System.out.println();         System.out.println("Should count up from 1");         countUp(n);     }            private static void countUp(int n)     {...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • the code needs to be modifed. require a output for the code Java Program to Implement...

    the code needs to be modifed. require a output for the code Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...

  • DEBUGGING. JAVA. Identify the errors in the following. There are no logical errors in this one...

    DEBUGGING. JAVA. Identify the errors in the following. There are no logical errors in this one just syntax issues. //start import java.util.Scanner; public class NumbersDemo {    public static void main (String args[])    {       Scanner kb = new Scanner(System.in);       int num1, num2;             System.out.print("Enter an integer >> ");       num1 = kb.nextInt();       System.out.print("Enter another integer >> ");       num2 = kb.nextDouble();       displayTwiceTheNumber(num1);       displayNumberPlusFive(num1);       displayNumberSquared(num1)       displayTwiceTheNumber(num2);       displayNumberPlusFive(num2);       displayNumberSquared(num2);    }   ...

  • JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole...

    JAVA: amortization table: Hi, I have built this code and in one of my methods: printDetailsToConsole I would like it to print the first 3 payments and the last 3 payments if n is larger than 6 payments. Please help! Thank you!! //start of program import java.util.Scanner; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.lang.Math; //345678901234567890123456789012345678901234567890123456789012345678901234567890 /** * Write a description of class MortgageCalculator here. * * @author () * @version () */ public class LoanAmortization {    /* *...

  • The part in bold is giving me an error. Ther error is that I cant convert...

    The part in bold is giving me an error. Ther error is that I cant convert an int to a boolean. The program asks the user to input two integer values and determines whether the first is divisible (without a remainder) by the second import java.util.Scanner; public class CheckDivisible { int isDivisible(int dividend, int divisor) { if(dividend % divisor == 0) return 1; else return 0; } public static void main(String[] args) { int dividend = 0; int divisor =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT