how can I get the only entered values from an array? - java

I am trying to make a program to print a multiplication table in which the user enters the number of table he wants (for example 3) , also enters the values of table he wants( 2,6,5 (random/unordered)), also enters the range of multiplier.
my code is printing all the elements present in the array.
please help me. ThankYou.
import java.util.Scanner;
class Addition
{
public static void main(String[] args) {
int j=0,k=0;
Scanner obj=new Scanner(System.in);
int arr[]=new int[32];
System.out.println("how many multiplication table do you want to print ? ");
int n=obj.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("Enter number whos table you want ");
for(j=1;j<=n;j++)
{
arr[j]=obj.nextInt(); break;
}
}
System.out.println("Enter range of multiplier");
int range=obj.nextInt();
for(int l=0;l<=arr[j];l++)
{
for(k=1;k<=range;k++)
{
System.out.println(" "+l+" * "+k+" = "+l*k);
}
}
}
}
the output I want will look somewhat like this(
how many multiplication table do you want to print ? =3 and on entering numbers 2,5,6 and range=4)
2x1=2
2x2=4
2x3=6
2x4=8
5x1=5
5x2=10
5x3=15
5x4=20
6x1=6
6x2=12
6x3=18
6x4=24

I made a few adjustments to carry out what i think you trying to accomplish. you could use an arraylist seen below:
class Addition{
public static void main(String[] args) {
int j=0,k=0;
Scanner obj=new Scanner(System.in);
ArrayList<Integer> typeMultiplicationTable = new ArrayList<Integer>();
//used Arraylist instead of an array
//int arr[]=new int[32];
System.out.println("how many table? ");
int n=obj.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("Enter number whos table you want ");
for(j=0;j<=n;j++)
{
typeMultiplicationTable.add(obj.nextInt());
break;
//arr[j]=obj.nextInt(); break;
}
}
System.out.println("Enter range");
int range=obj.nextInt();
for(int l=0;l<=typeMultiplicationTable.size()-1;l++)
{
for(k=0;k<=range;k++)
{
System.out.println(" "+typeMultiplicationTable.get(l)+" * "+k+" = "+typeMultiplicationTable.get(l)*k);
}
}
}}
and if you do end up using an array, you could achieve it as follows - i ended up removing one of the for loops.
class Addition{
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
System.out.println("how many table? ");
int n=obj.nextInt();
int arr[]=new int[n];
for(int j=0;j<=arr.length-1;j++)
{
System.out.println("Enter number whos table you want ");
arr[j]=obj.nextInt();
}
System.out.println("Enter range");
int range=obj.nextInt();
for(int l=0;l<=arr.length-1;l++)
{
for(int k=0;k<=range;k++)
{
System.out.println(" "+arr[l]+" * "+k+" = "+arr[l]*k);
}
}
}}

Related

How do I accumulate a sum of a series of input values?

//Modify the program from the previous exercise, so that it displays just the sum of all of the numbers from one to the input number. Be sure to test your program with several inputs.
// Example5.java
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) {
int count = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = in.nextInt();
while (count <= number) {
System.out.println(count);
++count;
}
}
Given that code I have to modify the program that it displays the sum from 1 to the input number.
You asked
How do I accumulate a sum of a series of input values?
In the mentioned practice you need to separate your numbers with whitespace, there are many more advance approach like using IntStream api.
public class Example5 {
public static void main(String[] args) {
int sum = 0;
System.out.println("Add your numbers to sum: ");
Scanner in = new Scanner(new Scanner(System.in).nextLine());
while (in.hasNext()) {
sum += in.nextInt();
}
System.out.println(sum);
}
}
This code gives an output based on the statement, "Given that code I have to modify the program that it displays the sum from 1 to the input number."
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) {
int sum = 0, number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
number = in.nextInt();
for (int i = 1; i <= number; i++) sum += i;
System.out.println(sum);
}
}

Java array and nextInt(); do not work properly

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 ;)

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.

User based Multiplication Table

Hi I need help with my code. Im trying to make a user base input multiplication table using a Scanner and a method, but i dont know how to get the user base input from the main method to the method i created, here is what i have so far:
public static void multiplicationTable(int i){
for (int i=1;i<=size;i++){
for (int j=1;j<=size;j++)
System.out.print("\t"+i*j);
System.out.println(); }
}
public static void main (String[] args) {
System.out.println("This program displays a multiplication table.");
Scanner size = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int n = size.nextInt ();
}
You can pass like :
System.out.println("This program displays a multiplication table.");
Scanner size = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int n = size.nextInt ();
multiplicationTable(n); \\ pass here
Actually your codes are pretty closed. Please see below (I have tested the codes):
public static void multiplicationTable(int size) {
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
System.out.print("\t" + i * j);
}
System.out.println();
}
}
public static void main(String[] args) throws Exception {
System.out.println("This program displays a multiplication table.");
Scanner size = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int n = size.nextInt();
multiplicationTable(n);
}

Insight with ending a loop by pressing the enter key in Java

I am in a low level java programming class, and I am having trouble figuring something my professor assigned to us. We originally made a program that added integers that were placed in an arraylist. She then asked us to make it as user friendly as possible, without having a specific amount of integers the user inputs. So I came up with this:
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
do
{
numbers.add((int) input.nextInt()); //inserting input into the arraylist
System.out.println("The sum is " + sum(numbers)); //test output
}while(input.hasNextInt()); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(ArrayList<Integer> list)
{
int total = 0;
for (int i = 0; i < list.size(); i++)
{
total += list.get(i);
}
return total;
}
}
Sorry for the clutter of comments, I'm trying to show any of you my mindset behind what I did. Thank you so much in advance for anyone that has any suggestions!
See if this helps where in you take an input from user to terminate the program.
public class CalculatorREDONE {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add or -1 to exit");
Scanner input = new Scanner(System.in);
// boolean nextAvailable = true;
while(true)
{
String nextVal = input.nextLine();
if(nextVal.isEmpty()) {
break;
}
numbers.add(Integer.parseInt(nextVal)); //inserting input into the arraylist
// System.out.println("The sum is " + sum(numbers)); //test output
} //while (!input.next().); // I believe this needs to change but I am unsure what it should be
System.out.println(sum(numbers));
//My Problem here is that the loop doesn't end, therefore cannot print this output
input.close();
}
public static int sum(List<Integer> list) {
int total = 0;
for (int i = 0; i < list.size(); i++) {
total += list.get(i);
}
return total;
}
}
Try this -- it takes the input as a string, checks the length. If the user just hits enter the length will not be greater than zero. This catches the number exception from the parseInt by confirming the user has ended their list.
Note that I didn't include your sum portion since it wasn't relevant to the question of breaking the loop. You'll need to re-add
import java.util.Scanner;
import java.util.ArrayList;
public class CalculatorREDONE
{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter any numbers you would like to add. ");
Scanner input = new Scanner(System.in);
String userinput = "xx";
int nextnum = 0;
while (userinput.length() > 0) {
try {
userinput = input.nextLine();
nextnum = Integer.parseInt(userinput);
numbers.add(nextnum);
System.out.println("Taken");
} catch (NumberFormatException e) {
System.out.println("Inputs complete");
}
}
System.out.println(numbers);
input.close();
}
}

Categories