Java loop goes 4 times for some reason - java

So I have this assignment where I need to loop user's input 6 times. the loop, after finishing, looped again for 3 more times. I didn't add a for lop before it so I don't know how to handle it.
Here's the code for the method:
public static int[] getPlayerNumbers(int[] playNums) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < playNums.length; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invlaid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;
}
I placed i to see the index and it goes 0 to 5 then returns to 0. I ran out of ideas, please help.

it seems your playNums has more than 6. try
public static int[] getPlayerNumbers(int[] playNums) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invlaid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;}

I've tested your code and it seems to work for me. The playsNums contains certainly more than 6 values.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] playNums ={1, 2, 3, 4, 5, 6};
getPlayerNumbers(playNums);
for (int playNum: playNums) {
System.out.println(playNum);
}
}
public static int[] getPlayerNumbers(int[] playNums)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < playNums.length; i++) {
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
while (playNums[i] < 1 || playNums[i] > 9) {
System.out.println("Invalid input. Please only enter 1-9. ");
playNums[i] = input.nextInt();
}
}
return playNums;
}
}

Try this
public static int[] getPlayerNumbers(int[] playNums)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 6; i++)
{
playNums[i] = input.nextInt();
if(playNums[i] < 1 || playNums[i] > 9){
System.out.println("Invlaid input. Please only enter 1-9. ");
getPlayerNumbers(playNums);
} else{
System.out.println("Please enter numbers from 1-9: " + i);
playNums[i] = input.nextInt();
}
}
return playNums;

Related

not sure why while loop isn't looping

I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}

Why is my while loop not stopping after I want it to?

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
}
}
} while (number != 0);
I am trying to have the user enter numbers (up to 10) and is stopped once the user enters 0. But, when 0 is entered it does not stop.
It is simply because you have an inner for loop, you're setting the number to 0 but the for loop still hasn't finished completing. Here would be the fix
This will finish executing after the user enters 10 numbers or enters 0, whichever comes first
Scanner scanner = new Scanner(System.in);
int[] arrayNumber = new int[10];
int maxNums = 0;
while (maxNums < 10) {
arrayNumber[maxNums] = scanner.nextInt();
if (arrayNumber[maxNums] == 0) break;
maxNums++;
}
This is much shorter and neater, more readable
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
} while (number != 0);
The point is that your code would work properly only if you enter 0 at the last iteration at for loop. You can explicitly break your loop to let the while loop process your zero value and stop the loop.
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
}
} while (number != 0);

I am unable to delete elements from within my array when i ask for user input

When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.

Problems with my for loops printing out my arrays

can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];

infinite loop when asking for number

Hi all thanks for taking the time, I am continuosly getting an infinate loop when i am inserting the variable m could anyone please take a look thanks.
public static void main program7_2(String args [])
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while((n%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while((m%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum =0;
for (int i = n; n<=m; i++)
{
if ((i%2) != 0)
sum = sum + i;
}
System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}
The problem of the program is to enter 2 odd numbers and get the sum of the odd numbers in between
Thanks and regards
Instead of n<=m in your for loop use i<=m since you are using i as your counter and not n
This is the error :
for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
if ((i%2) != 0)
sum = sum + i;
}
Why : this loop increments i but terminating condition is n<=m which is never met....so either do i<n Or i<m which ever suits you for terminating the condition!!
if u want to get the sum of nubers between those two use
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while ((n % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while ((m % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum= 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("Sum of the numbers between " + n + " and " + m + ": " + sum);
}
}

Categories

Resources