I'm trying to write an application that inputs three integers from the user and displays the sum, average, product, smallest and largest of the numbers. It also should print the three numbers in an ascending order (from smallest to the largest). I tried to return the results into one JOptionPane but the sortResult is not returning the user inputs. I probably tried to over simplify the sort algorithm and am not applying it correctly. Currently the sortResult is returning a jumbled string:
"Your numbers are: [l#23ab93od"
What is the easiest way to correct this? Here is the code:
// Calculations using three integers.
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Calculations {
public static void main( String args[] ){
int x;// first number
int y;// second number
int z;// third number
int sumResult;// sum of numbers
int avgResult;// average of numbers
int prodResult;// product of numbers
int maxResult;// max of numbers
int minResult;// min of numbers
String xVal;// first string input by user
String yVal;// second string input by user
String zVal;// third string input by user
xVal = JOptionPane.showInputDialog("Enter first integer:");// prompt
yVal = JOptionPane.showInputDialog("Enter second integer:");// prompt
zVal = JOptionPane.showInputDialog("Enter third integer:");// prompt
x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
sumResult = x + y + z;
avgResult = sumResult/3;
prodResult = x * y * z;
maxResult = Math.max(x, Math.max(y, z));
minResult = Math.min(x, Math.min(y, z));
int[] sortResult = {x, y, z};
Arrays.sort(sortResult);
String result;
result = "Your numbers are: " + sortResult +
"\n" + "The sum is " + sumResult +
"\n" + "The average is " + avgResult +
"\n" + "The product is " + prodResult +
"\n" + "The max is " + maxResult +
"\n" + "The min is " + minResult;
JOptionPane.showMessageDialog(null, result, "Results", JOptionPane.INFORMATION_MESSAGE );
System.exit(0);
}// end method main
}// end class Product
When you concatenate an object with a String, Java automatically converts to a string by using its toString method. The array type does not override the toString method, so when toString is used on it, it will use Object's toString method, which just returns the type of the object ([l is the type of an array of ints) # its hash code in hex.
To get a String that represents what an array contains, use Arrays.toString(arrayName), (in this case "Your numbers are: " + Arrays.toString(sortResult) + ...).
Also, since you know that your array contains three elements, you could also just use something like sortResults[0] + ", " + sortResults[1] + ", " + sortResults[2], if you wanted them to be in a different format that the one returned by Arrays.toString (if you did not know the number of elements, or had too many to type them all one by one, you would have to loop through them).
You can use Arrays.toString(array) or the other nice thing you can do is to use collection framework.
Here I am giving you an example
ArrayList<Integer> al = new ArrayList<>();
// to add three element or to do any common thing for any number of elements.
for(int i = 0; i < 3; i++)
al.add(JOptionPane.showInputDialog("Enter " + i + "th number:"));
System.out.println(al);
By using Collections provided by java, you can make sorting, finding max, min, etc very easy.
// finding minimum of all elements
Integer min = al.stream().min((Integer a, Integer b) -> a.compareTo(b));
// finding maximum of all elements
Integer max = al.stream().max((Integer a, Integer b) -> a.compareTo(b));
// sorting all elements
al.sort((Integer a, Integer b) -> a.compareTo(b));
Related
I have the following code, and I would like the user inputs to store, and then the code loop back with the next input storing also, until they hit "Q" which will then quit. I am not sure how to do it.
Also, I want my 2d array to be printed blank, instead of the default 0s, after the user sets the size. SO if the user says they want to input SIZE = 4x4 "row =1, column =2, input =7" it would print "These ZEROS would be BLANK
0000
0070
0000
0000
the input "row 2, column 1, input A it would print
0000
0070
0700
0000
My code so far
import java.util.*;
public class MainProg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many rows do you want for your matrix? ");
int row = in.nextInt();
System.out.print("How many columns do you want for your matrix? ");
int column = in.nextInt();
String[][] newArray = new String[row][column];
Array2 twoDArray = new Array2(row, column, newArray); //calling my class
do {
System.out.println("If you would like to set an, element press S: " + "\n" +
"If you would like to set an element, press G" + "\n" +
"If you would like to empty an element, press E" + "\n" +
"If you would like to print an element, press P" + "\n" +
"If you would like to quit, press Q");
String userInput = in.next();
if (userInput.equalsIgnoreCase("S")) {
twoDArray.setElement();
} else if (userInput.equalsIgnoreCase("G")) {
twoDArray.getElement();
} else if (userInput.equalsIgnoreCase("E")) {
twoDArray.clearElement();
} else if (userInput.equalsIgnoreCase("P")) {
twoDArray.printMatrix();
//you will do you toString here
} else if (userInput.equalsIgnoreCase("Q")) {
//this will quit the program
twoDArray.quitProgram();
}
//break;
} while (true);
}
}
import java.util.*;
public class Array2 {
MainProg main1 = new MainProg();
Scanner in = new Scanner(System.in);
private String [][] newArray;
private int row;
private int column;
public Array2(int row, int column, String[][] newArray) {
this.row = row;
this.column = column;
this.newArray = newArray;
}
public void getElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like to get in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to get in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
String getElement = newArray[userRow-1][userCol-1];
System.out.println(getElement);
}
public void setElement() {
System.out.println("What row would you like your element in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column would you like your element in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("What character would you like the element to be?");
String userChar = in.next();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[userRow][userCol] = String.valueOf(userChar);
}
public void clearElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like empty? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to empty? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
}
public void printMatrix() {
Scanner in = new Scanner(System.in);
//String result = " ";
System.out.println("The array is: \n");
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) {
System.out.print(newArray[i][j]);
}
//for (String[] row: newArray) THIS LEAD TO A PROBLEM
// Arrays.fill(row, " ");
System.out.println();
}
}
public void quitProgram() {
System.out.println("The system will now exit! BYE!!!");
System.exit(0);
}
}
I have EDITED my code so that I have answered some questions. Now my only problem left is getting my matrix to be initially filled with blanks " ", instead of the default "null". I attempted to use the Arrays.fill in my printMatrix method, however that lead to problems, it would not save the user input after the loop.
Your IndexOutOfBoundsException (now editted out) is due to you using row and column instead of userRow and userColumn in setElement, which are where you've stored the user inputs. row and column will refer to the classes member variables, which are both 5 since you set it up as a 5x5 matrix, so above the max index of 4. You also will need to conver the char to a string since your using a String[][]
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[row][column] = userChar;
The last line should be newArray[userRow][userColumn] = String.valueOf(userChar);. Though you probably want to check those values are less than row and column to avoid more of that exception.
Even with that fixed, your code currently has other issues. The biggest is that you're currently defininig and using a new array in most methods and not the member variable newArray, so the method calls to get/set/clear/print aren't using your instance like you expect, but new empty arrays each time. These should be manipulating this.newArray not creating their own to manipulate, which dies with their return. You'll need to work through fixing all of that before looking into looping over the user input and interacting with your array.
On the printing of 0's, that is a side affect of one of the above issues. In printMatrix you declare a new int[][] newArray and print that. The default value of int is 0, so you get all 0's. If you were using your String array you'd get all "nullnullnull.." for each row as String's default to null. If you want all blanks initially, you'll have to initalize the array to all empty strings in your constructor or handle the null when looping through the array printing a space instead.
On looping for user input, you'll also need to ask for it again inside of your loop before the while, as otherwise the user input will only be asked for once and you will forever loop with that option.
Good luck, this seems like a good excersize to familiarize yourself with OO and array maniupulation, but a lot of the issues in your code are outside the scope of a single SO answer and smells a bit like classwork. I got your example code fixed up and manipulating as you want with only a handful of changes, so youre close.
EDIT:
In the future, please don't continuously edit questions to reflect further development unless you leave the original in place and add to it and it still reflects a continuation of the original problem, as it makes answers and comments have no context. SO is meant more to be questions and answers about specific issues faced, not a forum for feedback on continued development. If you got past a specific problem via an answer, mark that answer as the solution and move any new issues into a new question, else you risk having your question closed. See the first few topics under https://stackoverflow.com/help/asking, especially https://stackoverflow.com/help/how-to-ask, to see what I mean. I'm being pretty gentle, but this community can not always be.
That being said, as you seem to be making a geniune effort here, here's a few more bits of advice based on your comments and edits.
If you want to prefill the rows with spaces, the
for (String[] row : newArray)
Arrays.fill(row, " ");
block of code would not go in print, as that would blank it out each time print is called. It should go into your constructor, so that it only happens once when the object is created.
Alternatively, if you wanted to deal with it in the print method, something like
System.out.print(newArray[i][j] == null ? " " : newArray[i][j]);
Would do the trick, using a ternary operator to print out " " instead of null when encountered.
You also don't need to new up the Scanner in those methods but its not affecting functionality.
This question already has answers here:
Sorting Parallel Arrays
(4 answers)
Closed 2 years ago.
I need help with a given assignment to me in our class. We are given an assignment where we are supposed to make a student record with the student's id, first name, last name, course, year level, our prelim grade, midterm grade, final grade, tentative and final grade. The problem revolves around the algorithm I should use to sort the elements in the following arrays in parallel order. Here is a part of my code.
System.out.print("Number of students to record? ");
count = Integer.parseInt(keyboard.nextLine());
id = new String[count];
names = new String[count];
course = new String[count];
yearLevel = new int[count];
pGrade = new byte[count];
mGrade = new byte[count];
tFGrade = new byte[count];
fGrade = new byte[count];`
showData(id, names, course, yearLevel, pGrade, mGrade, tFGrade, fGrade); // Invoke the method for displaying the array elements
// Show the students in sorted order
System.out.println("Sorted Data");
showData(id, names, course, yearLevel, pGrade, mGrade, tFGrade, fGrade);
}
public static void populateArrays(String[] id, String[] n, String[] c, int[] y, byte[] p, byte[] m, byte[] t, byte[] f) {
for (int index = 0; index < n.length; index++) {
System.out.print("Enter the id number of student " + (index + 1) + ":");
id[index] = keyboard.nextLine();
System.out.print("Enter the name of student " + (index + 1) + ":");
n[index] = keyboard.nextLine();
System.out.print("Enter the course of student " + (index + 1) + ":");
c[index] = keyboard.nextLine();
System.out.print("Enter the year level of student " + (index + 1) + ":");
y[index] = Integer.parseInt(keyboard.nextLine());
System.out.print("Enter the prelim grade of student " + (index + 1) + ":");
p[index] = Byte.parseByte(keyboard.nextLine());
System.out.print("Enter the midterm grade of student " + (index + 1) + ":");
m[index] = Byte.parseByte(keyboard.nextLine());
System.out.print("Enter the tentative final grade of student " + (index + 1) + ":");
t[index] = Byte.parseByte(keyboard.nextLine());
// compute the final grade of student as the average of prelim, midterm and tentative final grade
f[index] = (byte) ((1.0 * p[index] + 1.0 * m[index] + 1.0 * t[index]) / 3.0 + 0.5);
}
return;
}
This is the part I need help. I don't know what algorithm I should use to sort the element of the arrays. And if so, how should I put all 8 arrays in one sort algorithm? Here is the method.
public static void sortDataBasedOnNames(String[] id, String[] n, String[] c, int[] yLevel, byte[] p, byte[] m, byte[] t,
byte[] f) {
} // end of sortBasedOnNames method
Any help or advice will be greatly appreciated. As you can tell, I am all new to this and really trying my best to wrapped my head on how to solve this algorithm.
I think that by saying "parallel sorting" the array, you are referring to sort them all together following a certain constraint and not to the "parallel programming sorting approach" since you have said that you are new to this.
The problem is that you have to choose a field by which to start sorting all the arrays. Furthermore, you can solve the problem easily just by doing the following steps:
Creating a class: Student
Insert all the students' data
Call sorting method (based on the particular field).
For instance, if you want to sort the students' array based on their ID, you can just specify it in the sorting method.
In order to achieve step 3, you can do something like this:
Implement a Comparator and pass your array along with the comparator to the sort method which takes it as the second parameter.
Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
Otherwise, you can do that using a "lambda expression". A lambda expression is a short block of code that takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
I'm gonna attach you some useful link where you can find also the code to do that:
with more and more approaches:
How to sort an array of objects in Java?
Sorting array of objects by field
This question already has answers here:
How to convert string array to int array in java [duplicate]
(6 answers)
Closed 6 years ago.
I am making a code that stores sport scores and matches through user input however I have used a string array to store both string and int value - while this did not seem to be a problem at first I have realized that validation becomes tedious as you can equally store a string in the "score" section even though it is incorrect.
I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem.
The user input looks like this;
Home_Team : Away_Team : Home_ Score : Away Score
I want to be able to add all the Away/Home scores to produce an output like so;
Total Home score: x
Total Away Score: x
Here is my for loop so far,
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input
if (words.length == 4) {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["+ words[3].trim() + "]");
}else{
System.out.println("Your input was not valid.");
matches--;
invalid++;
The logic for my new code will be "If Element[] does not contain an int value print "Invalid input"
"I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem."
To make an integer from a String, use this :
int x = Integer.parseInt( some_string );
Java Split String Into Array Of Integers Example
public class Test {
public static void main(String[] args) {
String sampleString = "101,203,405";
String[] stringArray = sampleString.split(",");
int[] intArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
String numberAsString = stringArray[i];
intArray[i] = Integer.parseInt(numberAsString);
}
System.out.println("Number of integers: " + intArray.length);
System.out.println("The integers are:");
for (int number : intArray) {
System.out.println(number);
}
}
}
Here is the output of the code:
Number of integers: 3
The integers are:
101
203
405
I'm a student just starting out in Java; I get hung up on seemingly easy concepts and have had trouble finding the answer to this despite a lot of googling. The assignment asks to:
Prompt the user to enter the number of people
Create a String array of the given size
Prompt the user for the name of each person
Put each name in the String array you created
Use a Java for-each to print each name with the length of the name
The output should look something like:
"Person 1 is named Andrew, and their name is 6 characters long"
This is what I currently have coded.
System.out.print("Hello. Please enter the number of people: ");
int people = scan.nextInt();
String[] myPeople = new String[people + 1];
System.out.println("Enter the name of each person:");
for(int i = 0; i < myPeople.length; i++)
{
myPeople[i] = scan.nextLine();
}
for(String peoples : myPeople)
{
System.out.println(peoples);
}
As it stands right now, the program can collect input from the user, put it into an array, and then print the array back out.
Am I approaching this the wrong way? I can't think of how I would modify the last For to not just print all the names, and instead print out each one with the "Person X is named ... ", their name, and then the description of how many characters long their name is.
Read about string concatenation.
int j = 1;
for(String peoples : myPeople)
{
System.out.println("Person " + j + " is named " + peoples + " and their name is " + peoples.length() + " characters long");
j++;
}
+ operator is used for concatenation of the strings.
You are doing good. In last for loop you can just do something like:
int personNumber = 0;
for(String people: myPeople)
{
System.out.println(String.format("Person %d is named %s, and their name is %d characters long", personNumber + 1, people, people.length());
personNumber++;
}
And one thing I've noticed - why are you instantiating array using new String[people + 1]? Why this extra one person? Arrays indexes are numered from 0, so new String[5] would give you array of 5 persons.
Firstly, you should create an array of size people, not people + 1:
String[] myPeople = new String[people];
To produce output in the required the format, you need to use the + operator to join the strings together. Also, since the person's position in the array is required, you need to create a variable to store that:
int index = 1;
for (String person: myPeople) {
String output = "Person " + index + " is named " + person + ", and their name is " + person.length() + " characters long.";
System.out.println(output);
index++;
}
Alternatively, you can use print instead of println: (only showing code inside for loop)
System.out.print("Person ");
System.out.print(index);
System.out.print(" is named ");
System.out.print(person);
System.out.print(", and their name is ");
System.out.print(person.length());
System.out.println(" characters long.");
index++;
how can I look for an word in a array list? in my code I search the array by position using get, but I want to compare a string (from user input) to the elements of the array, and then if it's found print all the elements contained in the position where the string was found.
import java.util.ArrayList;import java.util.Scanner;
public class Shoes {
Scanner input = new Scanner(System.in);
ArrayList shoesList = new ArrayList();
public void Shoe1() {
int Shoe1;
String Color1;
float Size1;
float Price1;
System.out.println("Enter model of the shoe: ");
Shoe1 = input.nextInt();
System.out.println("Enter color of the shoe: ");
Color1 = input.next();
System.out.println("Enter size of the shoe: ");
Size1 = input.nextFloat();
System.out.println("Enter price of the shoe: ");
Price1 = input.nextFloat();
shoesList.add("" + "model: " + Shoe1 + "\n" + "color: " + Color1 +//adds the variables, shoe, color, size and
"\n" + "size: " + Size1 + "\n" +"price: " + Price1); //price to one spot of the array
}
public void getSpecific(int value){
//gets and specific value taking input from the user
int select = value;
System.out.println(shoesList.get(select));
}
so what i want to do is search by the model of the shoe, say i have a model 1, if i search for "model 1" i want the program to display all the information stored in the position of the array where model 1 is.
You have a List of String you can use either startsWith(String) or contains(CharSequence). However, you should probably move those fields into your Shoes class and store instances of Shoes in your List.
No problem!
So, we want to:
1. Loop over the shoeList
2. See which shoe has the text
3. Print that shoe
//Note: Instead of taking an int, its better to take all the String. Example "model 1".
public void printShoe(String value){
for(String shoe : shoeList){ //The sign ":" said that, for every String in shoeList,
//do the following
if(shoe.contains(value))
{System.out.println(shoe);break;}//Break will make it not print more than 1 shoe
}
}
This method will do it.
String getIfContainsUserInput(String userInputString)
{
for (String shoeString : shoesList)
{
if (shoeString.matches(".*" + Pattern.quote(userInputString) + ".*"))
return shoeString;
}
return null;
}