Finish input to array before printing all - java

I am trying to do input to an array until it is full and after that print the entire array. But I cannot get the loop to run until the array is full and after that print all.
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++){
course[i] = input.next();
grade [i] = input.nextInt();
if (i == course.length)
break;
//System.out.println("\nHow do you want to order course and grade?");
//System.out.print(" 1 - Ascending?\n"
// + " 2 - Decending?\n");
//System.out.println("Name and grade is " + course[i] + " " + grade[i]);
System.out.println(Arrays.toString(course)+(grade));
}
}
}
How can get the loop to run and then jump to the print statement?

the variable i in the loop can never be equal to course.length because the loop runs only until i < course.length. So the if block is redundant anyway.
The printing statement should be AFTER the for block, otherwise you'd be printing the array in each iteration.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade [i] = input.nextInt();
}
System.out.println(Arrays.toString(course)+(grade));
}

There should be a } after grade [i] = input.nextInt();.
And the following if is not necessary at all.

It seems the loop would do the job if it was closed after the two assignment statements. The check afterwards isn't useful and could be removed.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[2]; // creating array
int[] grade = new int[2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade[i] = input.nextInt();
}
System.out.println(Arrays.toString(course) + (grade));
}

if (i == course.length) is unnecesery because when i == length then for loop finish working and for-loop-body doesn't call so remove this line and put instead of it close loop "}"
Next is printing your array. Change the last line to:
System.out.println(Arrays.toString(course) + Arrays.toString((grade)));

Related

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

My arraylist size is a zero even though I've added items to the it

So I tried looking up this error (Exception in thread "main" java.lang.ArithmeticException: / by zero)
and figured that my arraylist size in the code below is zero. I can't understand why it is zero or how to solve it. Does it have to do something with the capacity of the array? I can't seem to figure out what's wrong with my code.
Btw, this code is for computing the average of all the elements in an arraylist and letting the user know what the average is.
I'm still a beginner at Java so I apologize if this may seem silly. Any help is appreciated!
import java.util.*;
public class ClassStuff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList <Integer> ();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
for (int i = 1; i <= myArray.size(); i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
int result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static int computeAvg(List <Integer> myArray) {
int sum = 0;
int avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
return avg = sum/myArray.size();
}
}
I'm assuming the lines:
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
gets the amount of elements you want to add to the arraylist, which we later add to the list through the for loop. In that case keep it in another variable called list_length, since userInput constantly changes in the for loop.
System.out.println("Please enter a number: ");
list_length = scan.nextInt();
Then change the for loop after this input to something like:
for(int i = 1; i <= list_length; i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
This is because you changed the end of the for loop to myArray.size(), but remember that it was already 0, so the for loop ends since 1 >= 0. What you probably wanted to do was to add list_length amount of numbers into the arraylist
I found your problem.
The problem was your for loop because somehow the arrayList didn't catch any of the elements during the loop.
I also made some adjustment for the method so it counts the average correct.
Here's an example
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList<>();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
myArray.add(userInput);
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
System.out.println(myArray);
double result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static double computeAvg(List <Integer> myArray) {
double sum = 0;
double avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
avg = sum / myArray.size();
return avg;
}
Output
myList = [4,5]
average = (4 + 5) / 2 (myArray.size())= 4.5
Hope it was useful!

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.

How to get array of strings or integers from users inside looping statement?

When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}

Basic Arrays in a Java Program

I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}

Categories