Couple issues I am having with my fibonacci code. If I want to find the location of number 5 in the array (input), the system says its location is 5, but it should say 6? Also, if I enter a number that is not in the array, the system says it is found in location 20 (example input 200). System should say it is "not found"
int totalFibos=20;
int fibs[] = new int[totalFibos];
int a=0;
int b=1;
int fib=0;
fibs[0]=0;
fibs[1]=1;
int fibCounter=2;
while(fibCounter<totalFibos)
{
fib=a+b;
a=b;
b=fib;
fibs[fibCounter]=fib;
fibCounter++;
}
System.out.println("\n\nThe first "+ totalFibos + " fibonacci numbers are: ");
int i=0;
while(i<totalFibos)
{
System.out.print(fibs[i]+" ");
i=i+1;
}
System.out.println();
int userInput=0;
i=0;
Scanner sc= new Scanner(System.in);
int found=0;
while(userInput!=-1)
{
System.out.print("Enter a number to search,(enter -1 to end the search): ");
userInput= sc.nextInt();
while (i<totalFibos)
{
if(userInput==fibs[i])
{
found=1;
break;
}
i++;
}
if(found==1)
System.out.println("The number: " + userInput + " is found at location: "+ i++);
else if (found==0)
System.out.println("The number: "+ userInput + " is not found");
}
if(userInput==-1)
System.out.println("\nThanks");
}
}
Note that you have ";" sign after if statement in
if(userInput==fibs[i]);
{
found=1;
break;
}
That is why it expression in {} is always executed.
Remove the ";" and add i++; somewhere inside the while loop for this to work.
Update:
Also reset your counter and result after every input. This should be the first thing inside your while loop:
found = 0;
i = 0;
Here is your refactored code :
int totalFibos=20;
int fibs[] = new int[totalFibos];
int a=0;
int b=1;
int fib=0;
fibs[0]=0;
fibs[1]=1;
int fibCounter=2;
while(fibCounter<totalFibos)
{
fib=a+b;
a=b;
b=fib;
fibs[fibCounter]=fib;
fibCounter++;
}
System.out.println("\n\nThe first "+ totalFibos + " fibonacci numbers are: ");
int i=0;
while(i<totalFibos)
{
System.out.print(fibs[i]+" ");
i=i+1;
}
System.out.println();
int userInput=0;
i=0;
Scanner sc= new Scanner(System.in);
int found=0;
while(userInput!=-1)
{
System.out.println("Enter a number to search,(enter -1 to end the search): "); //Shouldnt this be println ?
userInput= sc.nextInt();
i=0; //Reset it, else the second search would fail
found=0; //Reset it, else the second search would fail
while (i<totalFibos)
{
if(userInput==fibs[i]);
{
found=1;
break;
}
i++; //Change state of i
}
if (found==1) { //Wheres your bracket ?
System.out.println("The number: " + userInput + " is found at location: "+ Integer.toString(i+1)); //Just to be sure...
}
else if (found==0) {
System.out.println("The number: "+ userInput + " is not found");
}
}
if(userInput==-1)
System.out.println("\nThanks");
}
Hope it works and helps you !
Related
Ask the user to "Input a number: " 4 times.
If the input is not a number, ask again.
Output "success." after they have entered 4 numbers.
Please answer this code for me using while, if, if else and do statements.
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
This is very basic stuff but I am struggling.
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner
I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}
I'm new to Java so forgive me. I'm writing a small little Guessing Game program.
import java.util.Scanner;
public class GuessingGame {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int menuOption;
// Main Screen //
System.out.println("Guessing Game");
System.out.println("---------------------");
System.out.println("1.) Play Game");
System.out.println("2). Exit");
System.out.println();
while (true) {
System.out.print("Please select a menu option: ");
menuOption = userInput.nextInt();
if (menuOption == 2) {
System.out.println("Exiting the game. Thanks for playing!");
break;
} else if (menuOption == 1) {
System.out.println("Let's start the game!");
getRandomRange();
} else {
System.out.println("Sorry, that's not a valid option. Please try again.");
continue;
}
}
}
/**
* Determine the range of numbers to work with
*/
public static void getRandomRange() {
int min;
int max;
System.out.print("Choose a minimum number: ");
min = userInput.nextInt();
System.out.print("Choose a maximum value: ");
max = userInput.nextInt();
getRandomNumber(min, max);
}
public static void getRandomNumber(int min, int max) {
int randomNumber = (int) (Math.random() * (max - min + 1)) + min;
getAGuess(min, max, randomNumber);
}
public static void getAGuess(int min, int max, int randomNumber) {
int guess;
while (true) {
System.out.print("Guess a number between " + min + " and " + (max) + ": ");
guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
}
}
}
}
When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.
For example:
Guess a number between 0 and 5: I enter my guesses here on this one line only.
I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.
Hope this makes sense. Thanks!
If your goal is only to clear the console, then you could do:
Runtime.getRuntime().exec("cls");
Or if you are on Linux or OS X:
Runtime.getRuntime().exec("clear");
Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.
This won't work in IDE's.
If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.
You could also do:
System.out.print("\033[H\033[2J");
This will clear the screen and return the cursor to the first row.
A quick and dirty solution...
public class Main {
public static final void main(String[] data) {
Scanner userInput = new Scanner(System.in);
int min = 0;
int max = 10;
int randomNumber = (int) ((Math.random() * max) + (min + 1));
while (true) {
System.out.print("Guess a number between " + min + " and " + max + ": ");
int guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
} else {
for (int i = 0 ; i < 25; i++) {
System.out.println();
}
}
}
}
}
I have the following piece of code where I'm trying to get the user to only enter integers; if a string is entered then it would display a system out error message "please only enter numbers" and then it would show the "Enter your ID#:" again. I tried using the try/catch method but was not using it correctly -- still a beginner. I know I can use the "NumberFormatException" but not sure where. Can anyone help? Thanks!
//Get Customer ID and Account Number
do
{ System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
} while (!(match));
Exceptions should be for exceptional circumstances. I suggest you use a Scanner and hasNextInt() to just continue when it isn't an int. That is make a Scanner like,
Scanner input = new Scanner(System.in);
and then something like this would work,
do {
System.out.print("Enter your ID#: ");
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
custid = input.nextInt();
System.out.print("Enter your Account Number#: ");
custacctnum = input.nextInt();
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
If you really want to use try-catch it should look something like,
do
{
try {
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) &&
(people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname
+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println("" + (p+1) + ": " +cluster[p].year+","
+ cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname
+ ", what color car would you like?");
break;
}
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
} while (!(match));
#Elliott Frisch, I "played" around with it before I saw your answer and figured out how to use the try/catch. It was fairly simple, but I will look at the other option that you posted. With the updated code below when the user enters a string, it will display the error message and then take them to the "Enter your ID#" line to try again.
Thank you all so much for the quick response.
do
{
try{
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
}
} catch (NumberFormatException e)
{System.out.println ("Error! Please enter a number!");}
} while (!(match));
I am having a problem when i break out from remove part the code prints main menu options twice
There is no error in code and it runs properly but why does it print twice instead of once?
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
System.out.println("");
System.out.println("Your Name " + Name + " and Number " + Number + " has been saved!\n");
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
System.out.println("-------ALL NAME AND NUMBERS-------");
System.out.println("");
for (int j = 0; j < Test.size();) {
objectclass p = Test.get(j++);
System.out.println(j + ". Name: " + p.getName() + " - " + p.getNumber());
}
for (int j = 0; j < Test.size(); j++) {
System.out.println("");
System.out.println("Enter Index number to remove Contact from Phonebook!");
int v = input.nextInt();
int temp = (v - 1);
if (v >= 1 && v <= Test.size()) {
System.out.println("Name: " + Test.get(temp).getName() + " And Number: " + Test.get(temp).getNumber() + " has been removed!!");
System.out.println("");
Test.remove(temp);
} else {
System.out.println("Please enter number properly!!");
}
break;
}
}
if (x.equalsIgnoreCase("3")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
}
if (!z.equalsIgnoreCase(y)) {
System.out.println("Contact not found!!!");
}
}
}
}
}
}
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
this prints twice :/~
If this prints twice, you went 2 times thru the loop. Try to display the variable 'x' after reading it. I bet you have extra empty strings between your legitimate input.
What happens is that nextInt() doesn't consume the newline. Therefore, the next time you read x you read the end of the line after the value v.
As mentioned by #Aeshang please use Switch instead of if.
Secondly
if (x.equalsIgnoreCase("2")) {
block does not end before
if (x.equalsIgnoreCase("3")) {
Your remove part also includes search part. Not sure if this will solve the problem but first correct these things and check your answer.