Inputting integers in to an array Error? - java

The purpose of my code is to display the student number and their respective grade as follows:
Student Grade
1 53
2 45
So on...
I used a 5x2 array, in which the user can input the values for the grade...
However I run in to a problem, when inputting the grades, for some reason I have to input 3 values, out of all the 3 inputted values only the 3rd is considered.
My problems:
(1) Why is it that I am even able to enter 3 values per student (Should only be able to input 1 value per student).
(2) Why is it the 3rd value that is being considered?
Here is my code:
import java.util.*;
public class practice {
public static void main(String[] args) {
int[][] studentGrade = new int[5][2];
for(int i = 0; i<5; i++) {
studentGrade[i][0] = i+1;
}
for(int j = 0; j<5; j++) {
System.out.printf("Student %s: ", j+1);
Scanner input = new Scanner(System.in);
if(input.nextInt()>=0 && input.nextInt()<=100) {
studentGrade[j][1] = input.nextInt();
}
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j);
}
}
System.out.print("\nStudent \t Grade");
for(int s=0; s<5; s++) {
System.out.print("\n" + studentGrade[s][0] +"\t" + "\t " + studentGrade[s][1]);
}
}
}

input.nextInt() consumes the next integer in the stream.
You need to do this:
Scanner input = new Scanner (System.in);
for (int j = 0; j < 5; j++) {
System.out.printf("Student %s: ", j+1);
int num = input.nextInt();
if (num >= 0 && num <= 100)
studentGrade[j][1] = num;
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j+1);
}
}
This will make it so that you read the number being input only once, and then you use that number when checking boundaries and then setting the grade.

Related

Avoid line break in Scanner.nextInt()

I am new to Java. I have to show to terminal int coefficients from a 2D array.
I would like to have each value for the same seller in the same line.
There is a line break (due to Scanner ?). I have been looking for delimiter for system.in but I do not understand how to use it and if that is appropriate.
Please, may you help me ?
Thank you in advance
import java.util.Scanner;
public class Ventes {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.print("Enter the number of sellers ");
int nbrSellers = myObj.nextInt();
System.out.print("Enter the number of models ");
int nbrModels = myObj.nextInt();
int[][] sales = new int[nbrSellers][nbrModels];
for(int i = 1; i <= nbrSellers; i++) {
System.out.print("Seller " + i + " ");
for(int j = 0; j < nbrModels; j++) {
sales[i][j] = myObj.nextInt();
}
System.out.println();
}
}
}
Terminal result :
Enter the number of sellers 5
Enter the number of models 4
Seller 1 0
3
2
0
Final result in terminal
If I understand correctly, you wanna receive both inputs in the same line. If so, Daveid's comment is correct. you don't have to press enter so you can go with the following lines:
System.out.print("Enter the number of sellers and models (separated by a space): ");
int nbrSellers = myObj.nextInt();
int nbrModels = myObj.nextInt();
And just enter both numbers on the same line like so:
5 4
or you can use delimiters like this:
Scanner myObj = new Scanner(System.in);
System.out.print("Enter the number of sellers and models (separated by a comma): ");
String input = myObj.nextLine();
String[] splitValue = input.split(",");
int nbrSellers = Integer.parseInt(splitValue[0]);
int nbrModels = Integer.parseInt(splitValue[1]);
int[][] sales = new int[nbrSellers][nbrModels];
for(int i = 1; i <= nbrSellers; i++) {
System.out.print("Seller " + i + " ");
for(int j = 0; j < nbrModels; j++) {
sales[i][j] = myObj.nextInt();
}
System.out.println();
}
or (based on your comment below) if you have to use a for loop, use this:
for(int i = 0; i < nbrSellers; i++) {
System.out.print("Please enter " + nbrModels + " values for Seller " + (i + 1) + " (separated by a space): ");
for(int j = 0; j < nbrModels; j++) {
sales[i][j] = myObj.nextInt();
}
System.out.println();
}
and just input the numbers like so:
3 4 6 2 1

How to cast an int array to a double array java?

Currently working on a project that requests the number of classes a student has left, the amount of classes taken per term, and returns the number of terms left to graduate. I'm having some trouble figuring out how to cast an integer array to a double array to figure out the amount of terms needed. Also the result needs to round up as well. I'm very new to this so any suggestions are much appreciated and critiques on how to clean up my code, thanks in advance.
import java.util.Scanner;
public class main {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int [][] studentArray = new int [rows][columns];
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
if (j==0) {
System.out.print("Please enter the number of classes left for student " +(i+1)+ " : ");
studentArray[i][j] = input.nextInt();
}
else if (j>0) {
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
while (studentArray[i][j] >= 6) {
System.out.println("The number of classes per term for student " +(i+1)+ " is not valid!");
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
}
}
}
}
divide(studentArray);
}
public static void divide(int termsLeft[][]) {
for (int k = 0; k < termsLeft.length; k++) {
double result = termsLeft[k][0] / termsLeft[k][1];
if (k>=0) {
System.out.println("Student " +(k+1)+ " has " + result + " terms left to graduate.");
}
}
}
}
First of all their are some problems in your code which make it very ineffecient.
1)
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
}
In your inner and outer loop you don't have to use <= sign and subtract 1 from right value. you can use i < rows & j < columns.
2)
if (k>=0) {
System.out.println(...)
}
Their is no need to use the if statement as it is always true.
Now coming to your question.
Your can use the Math.round method to round double values into long (can store larger values than int).
double result = termsLeft[k][0]/termsLeft[k][1];
long round_result = Math.round(result);
So your final code is below :
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows: ");
int rows = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int [][] studentArray = new int [rows][columns];
for (int i = 0; i <= rows-1; i++) {
for (int j = 0; j <= columns-1; j++) {
if (j==0) {
System.out.print("Please enter the number of classes left for student " +(i+1)+ " : ");
studentArray[i][j] = input.nextInt();
}
else if (j>0) {
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
while (studentArray[i][j] >= 6) {
System.out.println("The number of classes per term for student " +(i+1)+ " is not valid!");
System.out.print("Enter the number of classes taken per term : ");
studentArray[i][j] = input.nextInt();
}
}
}
}
divide(studentArray);
}
public static void divide(int[][] termsLeft) {
for (int k = 0; k < termsLeft.length; k++) {
double result = termsLeft[k][0]/termsLeft[k][1];
long round_result = Math.round(result);
System.out.println("Student " +(k+1)+ " has " + round_result + " terms left to graduate.");
}
}
}

Array input not adding up. -- total += scoreArray[i];

This section of code below for some reason is not taking each array item made and adding them together.
I stepped through the debugger and the array items are being created and incremented but the total += scoreArray[i];does not seem to be adding up the numbers that have been input. Instead, I am just getting just the 1st input divided by the array length as the final output
public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];
return (total / scoreArray.length);
}
Full Code
package driver;
import java.util.Scanner;
public class TestScores
{
private double[] scoreArray;
public TestScores(double[] test) throws IllegalArgumentException
{
scoreArray = new double[test.length];
for (int i = 0; i < test.length; i++)
{
if (test[i] < 0 || test[i] > 100)
throw new IllegalArgumentException("Test scores must have a value less than 100 and greater than 0.");
else
scoreArray[i] = test[i];
}
}
public double getAverage()
{
double total = 0.0;
for (int i = 0; i < scoreArray.length; i++)
total += scoreArray[i];
return (total / scoreArray.length);
}
public static void main(String[] args)
{
int score = 0;
int scores = 0;
Scanner userInput = new Scanner(System.in);
System.out.print("Enter number of test scores: ");
score = userInput.nextInt();
double[] scoreArray = new double[score];
for (int i = 0; i <= score - 1; i++)
{
System.out.print("Enter test score " + (i + 1)+ ": ");
scoreArray[scores] = userInput.nextDouble();
}
TestScores testScore = new TestScores(scoreArray);
System.out.println(testScore.getAverage());
}
}
Please change your loop of accepting user score with following:
for (int i = 0; i <= score - 1; i++)
{
System.out.print("Enter test score " + (i + 1)+ ": ");
// scoreArray[scores] = userInput.nextDouble(); <-- value of scores is zero
scoreArray[i] = userInput.nextDouble();
}
You should use "i" instead of "scores" while populating scoreArray. Currently you are populating your "scoreArray" with only last entered user input.

create a program that prompts the user to enter a number between 1 and 15 and print the sum as shown: 1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10

I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}

Java 'for' loop with range

I am working on a basic program (console).
The program should allow the user to enter in various marks, until the mark entered exceeds 100. At this point the program should display a histogram. Each star represents a student who achieved a module mark in the range shown.
This is an example of the output.
0 - 29 xxx
30 - 39 xxxxx
40 - 69 xxxxxxx
70 - 100 xxxx
20 students in total.
As the user enters each mark, there ought to be a counter that increases in value and print the total number of marks entered.
I want to make sure that the program is as efficient as possible but also understandable
Code
Working with #Dici on collabedit I have an amazing answer to my question:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ranges = { 0,29,39,69,100 };
int[] inRange = new int[ranges.length - 1];
int mark;
do {
System.out.println("Enter Mark:");
mark = sc.nextInt();
for (int j=1 ; j<ranges.length ; j++)
if (ranges[j-1] <= mark && mark <= ranges[j]) {
inRange[j-1]++;
break;
}
} while (mark <= 100);
System.out.println(Arrays.toString(inRange));
String s = "The number of students that have scored between %d and %d is: ";
int k = 0;
for (int i=0 ; i<ranges.length - 1 ; i++) {
System.out.print(String.format(s,ranges[i] + k,ranges[i + 1]));
for (int r = 0; r<inRange[i] ; r++)
System.out.print("*");
System.out.println();
k = 1;
}
sc.close();
Thank you again for your amazing help!
As we did it together on Collabedit, here is a working code for your question :
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ranges = { 0,29,39,69,100 };
int[] inRange = new int[ranges.length - 1];
int mark;
do {
System.out.println("Enter Mark:");
mark = sc.nextInt();
for (int j=1 ; j<ranges.length ; j++)
if (ranges[j-1] <= mark && mark <= ranges[j]) {
inRange[j-1]++;
break;
}
} while (mark <= 100);
System.out.println(Arrays.toString(inRange));
String s = "The number of students that have scored between %d and %d is : ";
int k = 0;
for (int i=0 ; i<ranges.length - 1 ; i++) {
System.out.print(String.format(s,ranges[i] + k,ranges[i + 1]));
for (int r = 0; r<inRange[i] ; r++)
System.out.print("*");
System.out.println();
k = 1;
}
sc.close();
}
}
Okay. Now that makes sense. If you have a number
int mark = 3;
You can use an if statement
if(mark <= 10){
//do this
}else if(mark <= 20){
//do this
}
You can also use a switch statement, however personal preference leads me to almost always use if statements.
If you want "buckets" you could use
ArrayList<String> marksForStudent = new ArrayList<>();
the documentation for that is here.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Or, alternatively and probably what you want is a hashmap. With the student's name or other unique identifier as the key and then a collection to contain their marks.
HashMap<String, ArrayList<String>> gradesForStudents = new HashMap<>();
gradesForStudents.put("Marc",Arrays.asList("99","98","100"));
Something like that.
Quick suggestion: do not alter marksInsp inside the loop if that's your loop index.
Paulinho made the excellent suggestion of using the modulo operator. I'll extend that here to a map, since you didn't specify the upper mark limit:
public static void main(String[] args) {
int currentMark, currentBucket;
final int BUCKET_WIDTH = 30;
Map<Integer, Integer> markRanges = new HashMap<Integer, Integer>();
for(int i = 0; i < 101; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Marks: ");
currentMark = input.nextInt();
currentBucket = currentMark % BUCKET_WIDTH;
if(markRanges.containsKey(currentBucket)) {
// There's already an entry for this bucket
markRanges.put(currentBucket, markRanges.get(currentBucket) + 1);
} else {
// If there isn't, make a new entry
markRanges.put(currentBucket, 1);
}
// Print out grade buckets
for(Integer j : markRanges.keySet) {
System.out.println(String.format("There are %d students with scores between %d and %d", markRanges.get(j), j, j.intValue() + BUCKET_WIDTH - 1));
}
}
}

Categories