Inserting values into two array using scanner class in java - java

import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
}
}
}
This is my code, I want to take input name from user then the income of that person then again the name of another person
The above code is not arranged properly, I think there's problem in the for loop the sample output should be like:
Enter how many friends: 2
Enter name of friend 1 : #############
Enter income of friend 1 : ##############
Enter name of friend 2 : #############
Enter income of friend 2 : ##############

You should take inner for loop out.
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
for(int j = 0; j<arrayOfNames.length;j++)
{
System.out.print("\nEnter the income of friend " + (j+1) + " : ");
income[j] = scan.nextLong();
}
scan.close();
}
}
Besides, if you want to enter them in order, you should just use one for loop
import java.util.Scanner;
public class Demo3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter how many friends: ");
int numOfFriends = Integer.parseInt(scan.nextLine());
String arrayOfNames[] = new String[numOfFriends];
long income[] = new long[numOfFriends];
for (int i = 0; i < arrayOfNames.length; i++)
{
System.out.print("\nEnter the name of friend " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
System.out.print("\nEnter the income of friend " + (i+1) + " : ");
income[i] = scan.nextLong();
scan.nextLine();
}
scan.close();
}
}
As a side note, don't forget to close() scanner after its task is completed.

Related

How to calculate sum of elements of an array

I have this code where I'm able to calculate the average of marks but unable to calculate the sum and percentage.
And I want to print the name of the student under student name but I'm getting only the student number.
I tried understand more about these, but was unable to get through.
Could you please help me out?
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
String arrayOfNames[] = new String[nos];
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
DB[i][3] = (int) (DB[i][0] + DB[i][1] + DB[i][2] / 3); //calculating the Average Marks of Each Student
DB[i][4] = (int) (DB[i][0] + DB[i][1] + DB[i][2]);
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
You are initializing your arrayOfNames array to a length of zero always. You should be initializing it once you get the value of the variable nos ( similar to your initialization of 2d array DB)
You are creating the array of names, i.e, arrayOfNames as an array of length 0 because nos is initially zero.
Observe this:
int DB[][],nos=0; //nos is initialized to 0
String arrayOfNames[] = new String[nos]; //arrayOfNames is of size = nos,which is in turn equal to 0, hence arrayOfNames is basically an array which can't hold anything.
instead do this: just declare arrayOfNames and don't initialize it. ==> String arrayOfNames[];
define the string size after you accept the size, i.e, nos. So it should be as follows:
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
arrayOfNames[] = new String[nos]; //now define the size
...
This would ensure that the string is accessible outside the Input() function as well as is defined with a valid size.
Following corrections can make your code run..
package testProgram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
//here initaialise reference will null
String arrayOfNames[] = null;
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
//create string array object here
arrayOfNames = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
//take extra variable that holds total, it increases the readability of the code
int total = DB[i][0] + DB[i][1] + DB[i][2];
DB[i][3] = (total) / 3; //calculating the Average Marks of Each Student
DB[i][4] = total;
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
Arrays are not dynamic. either you declare its size before hand or you use Arraylist..
boolean loopNaming = true;
int i = 0;
//you are creating array of zero size, use ArrayList instead
// String[] name = new String[i];
ArrayList<String> nameList = new ArrayList<>();
while (loopNaming == true) {
System.out.printf("Enter name of student or done to finish: ");
String name = keyboard.nextLine();
//check if name is 'done'
if (name.equals("done")) {
loopNaming = false;
} else {
nameList.add(name);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
//nextLine positions cursor to next line
keyboard.nextLine();
}
i = i + 1;
}
System.out.println(nameList);

How to add more variables inside of loops java

Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}

Random poem generator

I need to create a random poem generator while using arrays and input from the user (the user needs to input a minimal of 3 adjectives and 3 nouns) then the program has to randomly combine an adjective with a noun (a noun and an adjective can not be re-used twice) and display it. There needs to be 3 lines in the poem. Here's my code but it doesn't function at all the way it's supposed to! Please tell me what i did wrong!
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2, adj;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
if (x >= 3){
String[] noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
String[] adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
poemline[0] = adj + noun2;
poemline[1] = adj + noun2;
poemline[2] = adj + noun2;
System.out.println(poemline[0]);
System.out.println("/t/t" + poemline[1]);
System.out.println("/t/t/t/t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}
Try this
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2 = null;
String adj = null;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
String[] noun = null;
String[] adjective = null;
if (x >= 3){
noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
Random rnd = new Random();
poemline[0] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[1] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[2] = adjective[rnd.nextInt(y-1)] +" " +noun[rnd.nextInt(x-1)];
System.out.println(poemline[0]);
System.out.println("\t\t" + poemline[1]);
System.out.println("\t\t\t\t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}

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

Taking same output twice times

/*
* (Sort students) Write a program that prompts the user to enter the number of students,
*the students’ names, and their scores, and prints student names in decreasing
*order of their scores.
*/
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
When i run this program;
run:
Enter number of students: 3
Enter the name of student:
Enter the name of student:
a
Enter the name of student:
b
Enter the score of student:
c
Exception in thread "main" java.util.InputMismatchException
// i got " Enter the name of student: " twice times instead of one.
The first thing that comes to mind (not sure if it is correct here) is that you type the number of students and press "enter". It reads the first int (the 3) and reads the "enter" as the first input for the first student.
Maybe try int numberOfStudents = Integer.ParseInt(input.nextLine());?
That way the newline wont be added to the students.
You just have to remove the first System.out.print("Enter number of students: "); as you are printing the phrase in your for loop for every student. Therefore you are printing it twice for the first student (one time before your loop and one time in your loop)
It's not a good idea to answer homework question in SO. But since you have tried some code, It's OK to answer the Q. Take a look:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}

Categories