Java Scanner Help

Associate
Joined
28 May 2008
Posts
346
Ok so for my university assignment I had to create a program that would give the "**nth**" line of P***asc**als tri**ang**le using Rec**urs**ion (inserting stars so classmates cant google my work!)

So my problem is, I have created the program and it works correctly but it doesnt ask the user for the nth line, I have coded it into the program (testing shows working correctly for random numbers) No matter what i do wenever i change this so it has a scanner and accepts an int from the keyboard it WILL NOT compile, any ideas or tips on how i can make this keyboard input with out messing things up --->

public class PascalsTriangle {

public static void main(String[] args) {
int numbersList[] = new int[0];
displayNthLine(numbersList, 19);
}
//so instead of inserting the number 19 into the code above i need to enter it via keyboard//

static void displayNthLine(int origList[], int desiredLine) {

// calculate the next line/row of the triangle
int newList[] = new int[origList.length + 1];
newList[0] = 1; // first item is always a 1

// calculate the new internal values
for (int i = 1; i < origList.length; i++)
newList = origList[i - 1] + origList;

newList[newList.length - 1] = 1; // last item is always a 1

// Display the newly calculated values on one line
for (int i = 0; i < newList.length; i++)
System.out.print(newList + " ");

System.out.println(); // end of the line

// repeat the process if we are not done.
if (newList.length < desiredLine)
displayNthLine(newList, desiredLine);
}
}

any help would be greatly appreciated ;)
 
Last edited:
Code:
public static void main(String[] args) {
  int numbersList[] = new int[0];
  System.out.println("Enter the number");
  Scanner sc = new Scanner(System.in);
  int Number = sc.nextInt();
  displayNthLine(numbersList, Number);
}

and put import java.util.Scanner; at the top of the file. You should do some error checking to stop prevent it bombing out when you don't get an integer entered, that's left as an exercise for the reader.
 
Last edited:
Code:
	public static void main(String[] args)
	{
		Scanner inputScanner = new Scanner( System.in );
		
		System.out.println( "Please enter a line number: " );
		int lineNumber = inputScanner.nextInt();
		
		int numbersList[] = new int[0];
		displayNthLine(numbersList, lineNumber );
	}

That worked for me. The displayNthLine method is unchanged.
 
Back
Top Bottom