Two arrays in for loop - java

How can I use a for loop asking for student[0]'s grade, [1]'s etc? As of now, my for loop is pointless.
public static void main(String[] args) {
//declare grade and student array
int[] grades = new int[5];
String[] students = { "Bill", "Tom", "Mark", "Nic", "Miguel"};
Scanner sc = new Scanner(System.in);
for(int i = 0; i < grades.length; i++) {
grades[i] = i + 1;
//user input of student's grade
System.out.print("Enter grade for " + students[0] + ": ");
grades[0] = sc.nextInt();
System.out.print("Enter grade for " + students[1] + ": ");
grades[1] = sc.nextInt();
}
}
There must be a better way than hardcoding each student and grade array.

You can take the input and assign it in the loop itself.
for(int i = 0; i < grades.length; i++)
{
System.out.print("Enter grade for " + students[i] + ": ");
grades[i] = sc.nextInt();
}
That's all. You do not need to repeat code as that is what the loop will do by accessing each element with the index i.
However, I am not sure what the line grades[i] = i + 1; accomplishes in your code, since you anyways overwrite that value with the one you get as input.

If i am interpreting your question correct, what you want to do is accept grade values from user using for loop? My answer is as below, I have also printed grades which are accepted.
public static void main(String[] args) {
//declare grade and student array
int[] grades = new int[5];
String[] students = { "Bill", "Tom", "Mark", "Nic", "Miguel"};
Scanner sc = new Scanner(System.in);
System.out.println("please enter the grades of students");
for(int i=0; i<students.length; i++){
grades[i]= sc.nextInt();
}
for(int i=0; i<grades.length; i++){
System.out.println(grades[i]);
}
}

Related

Using while loop on a user specified condition

So, this below is my code:
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
while((res.toUpperCase()).equals("YES")) {
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
for(int i=1; i<50; i++) {
names[i] = n;
}
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
for(int j=0; j<50; j++) {
rolls[j] = r;
}
}
for(int a=0; a<50; a++) {
System.out.println(names[a]);
System.out.println(rolls[a]);
}
}
}
What I want is to happen is that, the program should keep registering students name and roll no. until the array is full or the user ends it. How do I do it ? I got that far
You need to have the "continue" question in the while loop, and you don't need the for loop every time you insert a name.
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
int index = 0;
while(true) {
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
if(res.toUpperCase().equals("NO") || index == 50)
break;
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
names[index] = n;
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
rolls[index] = r;
index++;
}
for(int i=0; i<50; i++) {
System.out.println(names[i]);
System.out.println(rolls[i]);
}
}
}
A common approach when using fixed sized arrays is to use a separate int variable to track the current index position for a new item, as well as the total used slots in the array:
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int size = 50;
String[] names = new String[size];
int[] rolls = new int[size];
int counter = 0;
String res = "";
do {
System.out.print("Do you want to register a student ?(yes/no): ");
res = sc.nextLine().toUpperCase();
if (res.equals("YES")) {
System.out.print("Enter the student's name: ");
names[counter] = sc.nextLine();
System.out.print("Enter their roll number: ");
rolls[counter] = sc.nextInt();
sc.nextLine(); // clear enter out of buffer;
counter++;
}
} while (counter < size && res.equals("YES"));
for(int a=0; a<counter; a++) {
System.out.print(names[a] + " : ");
System.out.println(rolls[a]);
}
}
}

i wrote a code using array and methods to display numbers from the smallest o the largest numbers

i wrote a code using array and method that allow the user to enter any number of numbers and
display the numbers sorted from the smallest number to the largest number however the program works but it doesn't show the numbers here is the code that i wrote
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
Your displayNumbers() method is wrong. In the loop you wrote:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
You're trying to read again 4 doubles (everytime you call that method) and you're printing the whole array (which doesn't do what you'd expect). What you probably want is this:
System.out.print(numbers[i] + " " );
Your code is inefficient and unclear.
You don't need to create a new Scanner everytime and also why instead of println the array with Arrays.toString(double[]).
You should also make more cleaner instructions and variable names.
Here is an example of how the code should be
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}

Need help for get string in java

I want get first name when input the name with array and looping
Example :
Enter the name :
1. Alvin Indra
2. Sada Rika
Output :
1. Alvin
2. Sada
Code:
public static void main(String[] args) {
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
System.out.println("First Name : ");
for(int i=0;i<n;i++){
if(teman[i] == ' '){ // this is where I need help
System.out.println((i+1)+". "+teman[i].substring(0,i));
}
}
}
Here you go
String name = "John Smith";
System.out.println(name.split(" ")[0]);
Using this will replace that second for loop, you don't need to cycle through each letter to look for a space you can just use the split method on the string and specifiy the character in which to split the string up and then call the first element.
Updated complete implementation
import java.util.Scanner;
public class testest {
public static void main(String[] args){
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
for(int i=0;i<n;i++){
System.out.println("First Name : ");
System.out.println(teman[i].split(" ")[0]);
System.out.print("\n");
}
}
}
You are probably looking for using contains and indexOf methods of String class in java, to use them as :
if (teman[i].contains(" ")) {
System.out.println((i + 1) + ". " + teman[i].substring(0, teman[i].indexOf(" ")));
}

Filling and sorting parallel arrays from single user input

I have to accept a single user input of a string and an int ten times, separate them at the space into two parallel arrays. I then have to sort them, find average, etc. Everything I have found on parallel arrays has two different inputs for the string and int. How can I separate the single input into the two arrays?
public static void main(String args[]){
//double[] gradeArray = new double[10];
//String[] nameArray = new String[10];
String name = " "; //name substring
String num = " "; //int substring
String s = " "; //input String
int grade = Integer.parseInt(num); //parsing the numerical string to an int
int x = s.indexOf(' '); //index of " " space
name = s.substring(0, x);
num =s.substring(x + 1);
Scanner input = new Scanner(System.in);
int[] gradeArray = new int[10];
String[] nameArray = new String[10];
//looping to gather 10 user inputs
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
//not sure how to sepearate String s into String name and String num
}
System.out.println("Highest Grade: " + Grades.highestGrade(gradeArray));
System.out.println("Lowest Grade: " + Grades.lowestGrade(gradeArray));
System.out.println("Class Average: " + Grades.classAverage(gradeArray));
for(int i = 0; i < nameArray.length; i++){
System.out.print(nameArray[i] + ", ");
System.out.print(gradeArray[i]);
System.out.println();
// System.out.print(sort());
}
How can I separate the single input into the two arrays?
First, we will use the already declared array of double to store the grades.
double[] gradeArray = new double[10];
Second, we will use the already declared array of String to store the names.
String[] nameArray = new String[10];
Now, going on to the for loop, we can use the String#split() method to separate the name and the grade on the delimiter " " considering that there will be whitespace between the name and grade as you've mentioned.
for(int k = 0; k < 10; k++){
System.out.println("Input Student name and grade: ");
s = input.nextLine();
String[] tempArray = s.split(" ");
nameArray[k] = tempArray[0]; // store name to nameArray
gradeArray[k] = Double.parseDouble(tempArray[1]); // store grade to gradeArray
}

How to calculate the average grade of the values from an array?

Please help me..I've been working on this nonstop and i still cant get this to run the way i want it to.I am new to programming. i am not very good at using methods. i have a sample of my work here and my problem is how do i get the average of the grades and how do i print it on the console. when i run this code the last values inside the variable grade are the only values that display on the console. I also need to check the attendance...how do i do it?
i need this code for my finals.
package studentmonitoring;
import java.util.*;
public class StudentMonitoring {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Date date=new Date();
int[] attend1={},attend2,attend3,grade={};
String line="-------------------------------------------------------------------";
String[] idNum1={},idNum2={},gender={}, name1={},name2={},name3={},name4={},address={},sub={};
Scanner input=new Scanner(System.in);
int check=0,num=0;
System.out.println(line);
System.out.println("\t\t****STUDENT MONITORING****");
System.out.println(line);
System.out.println("\nGood day teacher, to start using this program input the following information first.\n");
System.out.println(line);
System.out.print("NAME OF SCHOOL: ");
String sName=in.nextLine();
System.out.print("ADDRESS OF SCHOOL: ");
String sAdd=in.nextLine();
System.out.print("SCHOOL IDENTIFICATION NUMBER: ");
String sId=in.nextLine();
System.out.println(line);
System.out.println("STUDENTS INFORMATION");
System.out.println("Enter the year and section of this class");
String yearSec=in.nextLine();
System.out.println("How many student information do you want to input? ");
int numberStudents=in.nextInt();
idNum1=new String[numberStudents];
name1=new String[numberStudents];
name2=new String[numberStudents];
name3=new String[numberStudents];
name4=new String[numberStudents];
attend1=new int[200];
attend2=new int[200];
attend3=new int[200];
address=new String[numberStudents];
grade=new int[100];
gender=new String[numberStudents];
idNum2=new String[numberStudents];
System.out.println("Enter the number of subjects you have: ");
int numSub=in.nextInt();
sub=new String[numSub];
in.nextLine();
for(int x=0;x<numSub;x++) {
System.out.print("Subjec #"+(x+1)+": ");
sub[x]=in.nextLine();
}
for(int x=0;x<numberStudents;x++) {
in.nextLine();
System.out.println(line);
System.out.println("Student #"+(x+1));
System.out.print("LAST NAME: ");
name1[x]=in.nextLine();
System.out.print("FIRST NAME: ");
name2[x]=in.nextLine();
System.out.print("MIDDLE INITIAL: ");
name3[x]=in.nextLine();
System.out.print("GENDER: ");
gender[x]=in.nextLine();
System.out.print("ADDRESS: ");
address[x]=in.nextLine();
System.out.print("ID NUMBER: ");
idNum1[x]=in.nextLine();
System.out.println(line);
System.out.println("Enter the grades here.");
System.out.println(line);
for (int a=0;a<numSub;a++) {
System.out.print(sub[a]+": ");
grade[a]=in.nextInt();
}
}
System.out.println("This is the list of the students info you've inputted.");
System.out.println("ID Number\t Name\t\t GENDER\t\t ADDRESS");
for(int x=0;x<numberStudents;x++) {
System.out.println(idNum1[x]+"\t\t"+name1[x]+" "+name2[x]+","+name3[x]+".\t\t"+gender[x]+"\t\t"+address[x]);
}
System.out.println("Subject\t\tGrades");
for(int x=0;x<numSub;x++) {
System.out.println(sub[x]+"\t\t"+grade[x]);
}
System.out.println(line);
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Enter the number of students you want: ");
Scanner scanner = new Scanner(System.in);
int numOfStudents = scanner.nextInt();
double[] grades = new double[numOfStudents];
double total = 0;
double currentGrade = 0;
for(int i=0; i<grades.length; i++) {
System.out.println("Grade achieved: ");
currentGrade = scanner.nextDouble();
grades[i] = currentGrade;
total += currentGrade;
}
scanner.close();
System.out.println(Arrays.toString(grades));
System.out.println("Average grade " + (total / numOfStudents));
}
Here we first set the size of the double array (which will populate the grades). Then we fill in the double array using a for loop and getting user input via scanner.nextDouble().
Here's an example:
double[] values = { 2.2, 3.6, 6.3, 3.6, 2.8, 8.5, 8.3, 8.3, 1.2, 10, 2.2, 5.6 };
double sum = 0;
for (int i = 0; i < values.length; i++)
sum += values[i];
System.out.println("Average: " + sum / values.length);
That answers your initial question.
But if you also are having problems to populate the array, you can do it:
int MAX = 3;
double[] values = new double[MAX];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < MAX; i++) {
System.out.print("Type the grade: ");
values[i] = scanner.nextDouble();
}
scanner.close();

Categories

Resources