Avoid line break in Scanner.nextInt() - java

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

Related

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

error: incompatible types: int cannot be converted to int[] & other errors

import java.util.Scanner;
public class BasketBallChart {
public static void main (String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter the first names of the 5 players: ");
String nameString = reader.nextLine();
String[] name = nameString.split(" ");
for (int i = 0; i < 5; i++) {
System.out.print("Enter points earned by " +name[i]+ ": ");
int pL = reader.nextInt();
int p[i] = pL;
}
for (int j = 0; j < 5; j++) {
System.out.println(p[j]);
}
}
}
So basically the first part asks the user to enter the names of 5 players (with spaces) which then I split into a string array.
The for loop I was trying to make it so I wouldn't have to put 5 separate printlns and inputs, so it would be less lines and look cleaner.
So I was trying to make it so each point would be associated with the number of the times the for loop has been run for example, say if "i" was 0 and I had entered Oliver for the first name in the first input, name[0] would be Oliver, which then I wanted it to be like the number of points you enter in the first for loop would then be p[0] therefore associated with Oliver, in such that they're both 0.
I used the second for loop for testing purposes.
I keep getting errors and I am not sure why.
Here you have two issues with your code:
1) You need to declare array of p before the loop like int[] p = new int[5];
2) Then inside loop assign value to each array element like p[i] = pL;
3) For being safe please check for length of name array like if (name.length == 5)
public static void main(final String[] args) {
final Scanner reader = new Scanner(System.in);
System.out.print("Enter the first names of the 5 players: ");
final String nameString = reader.nextLine();
final String[] name = nameString.split(" ");
if (name.length == 5) {
final int[] p = new int[5];
for (int i = 0; i < 5; i++) {
System.out.print("Enter points earned by " + name[i] + ": ");
final int pL = reader.nextInt();
p[i] = pL;
}
for (int j = 0; j < 5; j++) {
System.out.println(p[j]);
}
}
}
Change your code to
String[] name = nameString.split(" ");
int p[] = new int[5];
for (int i = 0; i < 5 && i < name.length; i++) { // also check name array length
System.out.print("Enter points earned by " +name[i]+ ": ");
int pL = reader.nextInt();
p[i] = pL;
}
This will move the declaration of the p array to before (and outside) of the for loop. I have also added code to check that the looping does not exceed the length of the name array.
As suggested below by #RolandIllig, the array p would be better of being named as points and the name arrays would be better off named as names - giving variables names which reflect their usage makes for easier to understand code.

Java is printing last number using array method, by ignoring other numbers

I'm trying to let my code print numbers I put in output but using array method.
package pkg11;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
for (int z = 1; z <= b; z++) {
System.out.println("Input your" + " " + z + " " + "number");
x = in.nextInt();
}
System.out.println();
int[] a = new int[x];;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The problem is when it's printing it only prints the last value, for example, I put that I want to put 3 numbers, the first was 1 the second was 2 the third was 3, it prints the third without putting the first 2.
Have a close look at the following code fragment of yours and try to spot the error:
for (int z = 1; z <= b ; z++) {
System.out.println("Input your" +" " +z +" " +"number");
x = in.nextInt();
}
// here you create the array
int [] a = new int [x];
If you didnt spot it: You create the array you want to save each integer in after you have read all values from the console. There is no way you can store the users input in the array, since it is not known at that time.
Then, what did you actually do?
You used the same variable x all the time x = in.nextInt();, overriding each input.
What can i do to solve the problem?
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
int[] a = new int[b];
for (int z = 0; z < b; z++) {
System.out.println("Input your" + " " + (z + 1) + " " + "number");
a[z] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
First, declare int[] a = new int[b]; before you read the values and assign each input the the array with a[z] = in.nextInt();. Also, i modified your loop index a little bit to make things easier.
Ok, what else can i do?
Apart from the user entering non numbers, this code is a little bit more bullet-proof! If you are looking for even more, you can use in.nextLine() and Integer.valueOf() to prevent the user from entering strings instead of numbers.
Scanner in = new Scanner(System.in);
int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");
amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
System.out.println("Please enter a number greater than one:");
amountOfNumers = in.nextInt();
}
int[] numbers = new int[amountOfNumers];
for (int i = 0; i < amountOfNumers; i++) {
System.out.println("Input your " + (i + 1) + " number: ");
numbers[i] = in.nextInt();
}
System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);

Adding columns and rows in a 2D array of String type?

I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.

Inputting integers in to an array Error?

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.

Categories