The code seems to run except what I am getting is not a matrix of a specified (by the user) size but what I think is a heap address
Here's what it returns when the user inputs 2 for the size and then 4 numbers:
Enter matrix size:
2
Enter a 2 by 2 matrix row by row: 2 3 4 5
The row-sort matrix is...[[D#3c954549BUILD SUCCESSFUL (total time: 8 seconds)
here is the code....thank you in advance.
import java.util.Scanner;
public class Exercise7_26M {
public static void main (String[]args)
{
//Prompt user for input of matrix size
System.out.println("Enter matrix size: ");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
double[][] m = new double [size][size];
//prompt user for input of array
System.out.print("Enter a " + size + " by " + size + " matrix row by row: ");
for (int row = 0; row < 2; row++)
for (int column = 0; column < 2; column++)
m[row][column] = input.nextDouble();
System.out.print("The row-sort matrix is..." + m);
}
Java arrays do not override toString() so you are getting the default implementation from Object. Instead, you can use Arrays.deepToString(Object[]) like
System.out.println("The row-sort matrix is..." + Arrays.deepToString(m));
Related
We have a High School activity where we utilize ArrayList methods to create a mean and median program. However, I encounter a problem when I inputted 20 data as shown below. All answers and suggestions are appreciated.
THE PROBLEM:
Create a MeanMedian2 class so that the user can enter any number of values up to 20. If the list has an even number of values, the median is the numeric average of the values in the two middle positions. Allow the user to enter 9999 to quit entering numbers.
//https://www.softwaretestinghelp.com/java-arraylist-tutorial/
//https://stackoverflow.com/questions/16242733/sum-all-the-elements-java-arraylist
//https://stackoverflow.com/questions/16242733/sum-all-the-elements-java-arraylist
//https://stackoverflow.com/questions/22023053/how-do-i-print-a-single-item-on-a-array-list
import java.util.*;
class MeanMedian2{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
int reference = 0;
int count = 1;
int ender = 9999;
while(true){
System.out.println("Enter number " + count + ":" );
int num = input.nextInt();
if (num == ender){
break;
}else{
numbers.add(num);
reference += 1;
count += 1;
}
}
//Mean
double sum = 0;
for (int i = 0; i < numbers.size(); i++)
sum += numbers.get(i);
double mean = sum/numbers.size();
//Median
int median;
Collections.sort(numbers);
int length = numbers.size();
int oddOrEven = length % 2;
int Odd = (length + 1)/2;
if (oddOrEven != 0 ){
median = numbers.get(Odd - 1);
}else{
int a = numbers.get((length/2)-1);
int b = numbers.get(length/2);
median = (a+b)/2;
}
//Final
System.out.print("You entered: ");
for(int i = 0; i < numbers.size() - 1; i++){
System.out.print(numbers.get(i) + ", ");
}
System.out.println(numbers.get(length-1));
System.out.println("The mean is " + mean + " and the median is " + median );
}
}
Instance 1:
/**
Enter number 1:
25
Enter number 2:
50
Enter number 3:
500
Enter number 4:
550
Enter number 5:
450
Enter number 6:
600
Enter number 7:
200
Enter number 8:
10
Enter number 9:
700
Enter number 10:
9999
You entered: 10, 25, 50, 200, 450, 500, 550, 600, 700
The mean is 342.77777777777777 and the median is 450**/
Instance 2. I inputted 20 data and 1 9999 to stop (21 in all)
/**
javac MeanMedian2.java
java MeanMedian2Exception in thread "main"
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MeanMedian2.main(MeanMedian2.java:19)**/
Change the while loop condition.
while(reference != 20){
A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}
This is part of a school assignment which I've already turned in, I was graded down in one portion because the total sum of the random numbers was supposed to be adding the individual numbers together, not each line.
So if the lines read:
1 2 3
4 5 6
The total should be 21, not 579 as my program is doing now. I've really been struggling trying to figure this out. I tried generating a different random number object for each integer, for a total of three of them but that completely screwed up my output.
We're learning arrays next week, and after researching online I could do this easily with an array, but the assignment was to be done without arrays. How can I sum each entry individually? Thanks for any help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;
System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");
System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
gameType = input.nextInt();
System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");
System.out.print(" How many games should we play? ");
gameTimes = input.nextInt();
System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" +
" The numbers randomly selected were: ");
for(int i = 0; i < gameTimes; i++)
{
lotNum = 0;
for(int j = 0; j < gameType; j++)
{
randomNums = (new Random()).nextInt(10);
lotNum = (lotNum * 10) + randomNums;
System.out.print(" " + randomNums);
}//end nested for loop
System.out.println();
sum += lotNum;
}//end for loop
System.out.println("\n\nThe total of all of the numbers was " + sum );
input.close();
}//end main method
}//end lottery class
Change
lotNum = (lotNum * 10) + randomNums;
to
lotNum += randomNums;
So I was tasked to write a program that can create two matrices and then add them both together. I must ask the length and height of matrix 1, and then ask the length and height of matrix 2. Which I did here:
Scanner keyboard = new Scanner(System.in);
int length1, height1, length2, height2;
System.out.println("Welcome to the matrix adder program");
System.out.println(" ");
System.out.println("Please enter the length of the first matrix");
length1 = keyboard.nextInt();
System.out.println("Please enter the height of the first matrix");
height1 = keyboard.nextInt();
System.out.println("Please enter the length of the second matrix");
length2 = keyboard.nextInt();
System.out.println("Please enter the height of the second matrix");
height2 = keyboard.nextInt();
int[][] a = new int[length1][height2];
int[][] b = new int[length2][height2];
Then I need to enter a value for matrix 1 row 1, column 1, row 1, column 2, and so on until it meets the dimensions of the array. So I put
for (int i = 1; i < length1 + 1; ++i)
{
for (int j = 1; j < height1 + 1; ++j)
{
System.out.println("Please enter a value for matrix 1 space "+ i + "," + j);
a[i][j] = keyboard.nextInt();
}
}
And this is where I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at MaxtrixAddition.main(MaxtrixAddition.java:32)
It would need to output something like this:
Please enter a value for matrix 1 space 1, 1
4
Please enter a value for matrix 1 space 1, 2
1
Please enter a value for matrix 1 space 2, 1
8
Please enter a value for matrix 1 space 2, 2
7
Please enter a value for matrix 2 space 1, 1
1
Please enter a value for matrix 2 space 1, 2
3
Please enter a value for matrix 2 space 2, 1
2
Please enter a value for matrix 2 space 2, 2
4
What would I need to do to get rid of that error?
I hope that I understood what you want to do.
Arrays start at position 0.
So your code snip should be:
for (int i = 0; i < length1; ++i)
{
for (int j = 0; j < height1 ; ++j)
{
System.out.println("Please enter a value for matrix 1 space "+ i + "," + j);
a[i][j] = keyboard.nextInt();
}
}
thank you for your help.
Here is the assignment:
Computer Technology Instructor has a small class of 10 students. The instructor evaluates the performance of students in the class by administering 2 midterm tests and a Final Exam.
Write a program that prompts the instructor to enter the 10 grades of midterm 1 and store these numbers in an array. Next prompt for the 10 grades of midterm 2 and store these numbers in a different array. Next prompt for the 10 grades of the Final Exam and store these in a different array. Next add midterm1 to midterm2 to Final and store the totals in a different array. Next, scan the array that has the totals and identify the minimum grade and maximum grade. Inform the instructor of the minimum grade and maximum grade.
The two bold phrases are where I am having problems. Everything works except for the minimum grade and maximum grade. Here is what it tells me, after I've only entered numbers between 65 and 100:
The highest test score is: 276 The lowest test score is: 249
Here is my code:
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);
// Prompt for the 1st mid term
int [] midTerm1 = new int[10];
int [] midTerm2 = new int[10];
int [] finalExam = new int[10];
int [] grades = new int[10];
for (int i = 0; i < midTerm1.length; i++){
System.out.println("Enter the 10 Mid Term 1 grades: ");
midTerm1[i] = input.nextInt();
}
// Prompt for the 2nd mid term
for (int i = 0; i < midTerm2.length; i++){
System.out.println("Enter the 10 Mid Term 2 grades: ");
midTerm2[i] = input.nextInt();
}
// Prompt for Final grades
for (int i = 0; i < finalExam.length; i++){
System.out.println("Please enter a Final Exam grade: ");
finalExam[i] = input.nextInt();
}
for (int i = 0; i < grades.length; i++){
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
}
int minGrade = grades[0];
int maxGrade = grades[0];
for (int i = 0; i < grades.length; i++)
{
if (minGrade > grades[i])
minGrade = grades[i];
if (maxGrade < grades[i])
maxGrade = grades[i];
}
System.out.print("The highest test score is: " + maxGrade);
System.out.print("The lowest test score is: " + minGrade);
}
}
Edit:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]);
Your code may in fact be correct. Since you're adding your three test scores together, expect that the grade will be not between 65 and 100 but rather between 195 and 300.
If you want a number between 65 and 100, this needs to be divided by 3:
grades[i] = (midTerm1[i] + midTerm2[i] + finalExam[i]) / 3;
or else find some other way to normalize the grades. For instance, if the final is 50% of the grade then you could have:
grades[i] = (25 * midTerm1[i] + 25 * midTerm2[i] + 50 * finalExam[i]) / 100;
But again your current solution may in fact be the correct one.