Java array and nextInt(); do not work properly - java

Hello guys I am having a problem with an array and a .nextInt(); this is causing my output line at the 3rd prompt to shift up instead of under, and seriously cannot figure out what's wrong.
I have tried .hasNextInt(); but nothing, it actually gives me an error, so here is the code:
import java.util.Random;
import java.util.Scanner;
public class birthday {
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn); //my problem
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //my problem
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2];
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
// Method for calculations
public static double compute(int numOfSimulation, int numOfPeople)
{
for (int i =0; i < numOfPeople; i++)
{
Random rnd = new Random(1);
//Generates a random number between 0 and 364 exclusive
int num = rnd.nextInt(364);
System.out.println(num);
System.out.println(num / 365 * numOfPeople * numOfSimulation);
}
return numOfPeople;
}
}

Found it!!!!!!!!!!!
do this:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return(userInput);
}
To return the array
Let me know!

I actually don't think you can do it there with that userInput, I am saying this because the methodology of doing this program is quite arcane.
You are then calling 2 arrays at prompting, I wonder if you might change that to one what will change such as:
// User input prompt where you make the simulation. For people and return them as an array
public static int[] promptAndRead(Scanner stdIn)
{
System.out.println("Please enter the number of simulations you want to do: ");
int[] userInput =new int [2]; //CHANGE THIS TO 1?
userInput[0]= stdIn.nextInt(); //my problem
System.out.println("Please enter the size of the group you want : ");
int[] userInput1 = new int [2]; //CHANGE THIS TO 1?
userInput[1] = stdIn.nextInt();
int a = userInput[1];
while (a<2 || a>365)
{
System.out.println("please type the number that is between 2~365");
}
System.out.println();
return promptAndRead(stdIn);
}
As also the return promptAndRead(stdIn); might be part of the problem
Don't know though just trowing suggestions at Markov ;)

Related

How to enter Uniquely entered values into an array

My homework question is to Create a procedure called NoDuplicates which will prompt the user to enter 7 unique integers. As the user enters the numbers, ask them to re-enter a number if it has been entered previously. Output the 7 unique numbers.
I have tried a lot of different combinations of while and for loops but nothing works
import java.util.Scanner;
public class arrayexcersisespart3num1 {
public static void main(String []arg) {
Scanner input = new Scanner(System.in);
noDuplicates(input);
}
public static void noDuplicates(Scanner input) {
boolean check = true;
int jumbo;
int[]noDuplicates = new int [7];
System.out.println("Please enter a unique Name");
for (int i = 0; i<noDuplicates.length;) {
System.out.println("Enter a number");
jumbo = input.nextInt();
while(check ==true|| i>0) {
check = false;
System.out.println("Please enter another number");
jumbo = input.nextInt();
if (jumbo==(noDuplicates[i])) {
check = true;
System.out.println("this Name has been previously added. Please choose another number");
}
}
jumbo = noDuplicates[i];
System.out.print("this Number has been previously successfully added in position ");
System.out.println(i+1);
check = false;
i++;
}
}
}
I don't understand your code, but:
final int N = 7; // Constant, used multiple times throughout the program
Scanner sc = new Scanner (System.in);
int[] noDuplicates = new int[N];
noDuplicates[0] = sc.nextInt();
for(int i=1; i<N; i++){ // Loops through the array to put numbers in
int query = sc.nextInt(); // Number to be put into the array
for(int j=0; j<i-1; j++){
if(noDuplicates[j] == query){ // If they are the same
i--;
continue; // Tells them to input a new number, skips all code ahead
}
}
noDuplicates[i] = query;
}
Try this logic of Collection.contains then add it in collection. It will ask the input from user from console and check whether data store in List or Not. Like this it will ask the value from user for 7 unique time on list used that
public void uniqueDataCheckOnConsoleOnLimitByList() {
int capacity = 7;
List<String> dataList = new ArrayList<>(capacity);
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (dataList.contains(s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
dataList.add(s);
capacity--;
}
}
}
As i did not check the requirement on Array. Please check it in case of array.
public void uniqueDataCheckOnConsoleOnLimitByArray() {
int capacity = 7;
String data[]= new String[capacity];
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (containsArray(data, s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
data[capacity-1]=s;
capacity--;
}
}
}
public boolean containsArray(String data[],String input){
for(String s:data){
if(input.equalsIgnoreCase(s))
return true;
}
return false;
}

How to allow user to make edits to an array

I must create 3 arrays, one to hold 5 product IDs, one to hold 5 product prices, and one to hold 5 product inventories. I need a method to print all the product IDs, print all product prices, and print all the inventories. I need a method to allow user to make edits to any of the product IDs, product prices, or inventories (this is the method I am struggling with). After each edit is made I must reprint all the data. I also need a method to print all the correct data after all the edits are made and an extra column, the total price for each product and the overall price. Thanks in advance for any help!
import java.util.Scanner;
public class Inventory {
d public static void main(String[] args) {
String[] productIDArray = new String[5];
double[] priceArray = new double[5];
int[] inventoryArray = new int[5];
input(productIDArray, priceArray, inventoryArray);
print(productIDArray, priceArray, inventoryArray);
edit(productIDArray, priceArray, inventoryArray);
}
public static void input (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Enter the product ID, the price and inventory: ");
productIDArray[i] = input.next();
priceArray[i] = input.nextDouble();
inventoryArray[i] = input.nextInt();
}
}
public static void print (String[] productIDArray, double[] priceArray,
int[] inventoryArray) {
for (int i = 0; i < 5; i++) {
System.out.println(productIDArray[i]);
System.out.println(priceArray[i]);
System.out.println(inventoryArray[i]);
}
}
public static void edit (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
Scanner input = new Scanner(System.in);
int whatToEdit = 0;
String oldProductID = " ";
String newProductID = " ";
double oldPrice = 0;
double newPrice = 0;
int oldInventory = 0;
int newInventory = 0;
String yesNo = " ";
while (true) {
System.out.print("Do you want to make an edit? (Y/N)");
if (yesNo = y.toUppercase) {
System.out.print("Enter what you want to edit: ");
System.out.print("Do you want to edit a product ID (1), price (2), or
inventory (3)? ");
whatToEdit = input.nextInt();
if (whatToEdit == 1) {
System.out.print("Enter the product ID you want to edit and the edit: ");
productID = input.next();
newProductID = input.next();
productIDArray[product] = newProductID;
} else if (whatToEdit == 2) {
System.out.print("Enter the price you want to edit and the edit: ");
oldPrice = input.nextDouble();
newPrice = input.nextDouble();
priceArray[oldPrice] = newPrice;
} else if (whatToEdit == 3) {
System.out.print("Enter the inventory you want to edit and the edit: ");
oldInventory = input.nextInt();
newPrice = input.nextInt();
inventoryArray[oldInventory] = newInventory;
}
}
} else if (yesNo == n.toUppercase) {
break;
}
print(productIDArray, priceArray, inventoryArray);
}
public static void totalPrice (String[] productIDArray, double[] priceArray, int[] inventoryArray) {
}
}
First check which array they want to edit. Then check which part of the array they want to change. You then just take the users input for which piece of the array and the new value for that piece.
Lets say they chose inventory array. Get input for which part of array and then the number to replace it with.
inventoryArray[usersinput] = //Users next inputted number they want to replace it with
EDIT:
To check which array they want to edit you could do something like this.
System.out.print("Enter 1 for product array, 2 for price array, and 3 for inventory: ");
Then read the users input again and use an if or switch statement to decide what to do with whichever array they chose.
EDIT 2:
Problems with your compare and toUppercase. I can't find where your defining the variable 'y' which you are using with your toUpperCase(). So you also need to define that somewhere.
if (yesNo.equals(y.toUppercase()))

populating the array with the user input

i apologize i know this looks simple but i'm kinda new to coding. the goal of the program is to take inputs from the user starting at index 0 and then save the inputs into the array. i'm probably close to solving this but i need some help.
here is the code:
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[numberOfGrades] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
Your logic is a bit off. numberOfGrades is the.. well.. number of grades. And when you do this: grades[numberOfGrades] = input.nextInt(); then you put the user's input in the grades array in location numberOfGrades, which you don't want.
What you do want is:
do {
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
This way, the array in location counter is accessed, and the user's input is placed inside it in the correct location.
Also, to calculate the average of the grades, like you are trying to do in the end of your program, you should do:
double sum = 0;
for (int grade : grades)
sum += grade;
And then your average will be:
average = 1.0d * sum / grades.length;
You can just as well put this summing logic inside your do-while loop and avoid the extra loop I introduced.
this instruction
grades[numberOfGrades] = input.nextInt();
must be replaced by
grades[counter] = input.nextInt();
try this ...
The thing that you were doing wrong is in the do while loop you were inserting value in the same array index grades[numberOfGrades] = input.nextInt(); should be replaced by grades[counter] = input.nextInt();
public class ArrayTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int numberOfGrades;
int counter = 0;
System.out.println("This program averages the grades you input.");
System.out.println("Please enter the number of grades you'd like averaged: ");
numberOfGrades = input.nextInt();
int[] grades = new int[numberOfGrades];
do
{
System.out.println("Please enter grade number " + (counter+1) + ": ");
grades[counter] = input.nextInt();
counter++;
} while (counter < numberOfGrades);
System.out.println("The number of grades you wanted averaged was: " + grades.length);
}
}
You can try like this
public class ArrayTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("enter number of elements");
int n=input.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=input.nextInt();
}
for(int i: arr){ //for printing array
System.out.println(i);
}
}

How do I output a TABLE with names and scores with only using Arrays and Methods?

I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.

Error in the output of my java program

I am trying to do a java program but I am having a problem with the output.
Here is the error I get when I input the information.
Enter social security number:12345678
Enter salary3000
Please input next security numbers or -1 to quit:12345666
Enter salary2122
Please input next security numbers or -1 to quit:900000000
Enter salary3000
Please input next security numbers or -1 to quit:-1
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ':'
at java.util.Formatter.checkText(Formatter.java:2547)
at java.util.Formatter.parse(Formatter.java:2533)
at java.util.Formatter.format(Formatter.java:2469)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Salaries.output(Salaries.java:57)
at Salaries.main(Salaries.java:19)
And here is my code so far..
import java.util.Scanner;
public class Salaries {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int[] ssNumbers = new int [10];
double[] salaries = new double [10];
double[] nSalaries = new double [10];
int c;
c = inputData (ssNumbers, salaries);
raise (salaries, c);
output (ssNumbers, salaries, nSalaries);
}
public static int inputData (int[]ssn, double[]sals){
int c = 0;
Scanner input = new Scanner (System.in);
int ssNum;
System.out.print("Enter social security number:");
ssNum = input.nextInt();
while (ssNum != -1) //using while loop.
{
ssn[c] = ssNum;
System.out.print("Enter salary");
sals[c] = input.nextDouble();
c++;
System.out.print("Please input next security numbers or -1 to quit:");
ssNum = input.nextInt();
}
return c;
}
public static void raise (double[] salaries, int c)
{
double[] salaryraise = new double [10];
for (int i = 0; i < c; i++ )
salaryraise[i] = salaries[i]*.02;
}
public static void output (int[] ssNumbers, double[] salaries, double[] nSalary )
{
System.out.printf("%-20s%-20s%-20s%:\n", "Social Security Number", "Salaries", "Salary After Raise");
for (int i = 0; i < salaries.length; i++)
System.out.printf("%d %.2f %.2f", ssNumbers[i], salaries[i], nSalary[i]);
return;
}
}
You have a "%:" in this line you'll wanna remove. (because it's not a valid specifier)
System.out.printf("%-20s%-20s%-20s%:\n", "Social Security Number", "Salaries", "Salary After Raise");
:)
Try changing the line:
System.out.printf("the salary after raise is %f\n:", salaryraise);
To:
System.out.println("the salary after raise is: " + salaryraise);
The % character at the end of format make the error.
Should delete it lis below:
System.out.printf("%-20s%-20s%-20s%:\n",
>>System.out.printf("%-20s%-20s%-20s:\n",

Categories