Multiarray inputs - java

I am unable to create a loop to add hours to a multi-array. When I use the method Hours there is an error. I suspect my for-loop is not capturing the input.
import javax.swing.JOptionPane;
public class Gain
{
// Defining array names.
String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”};
int[][] hours = new int[10][3];
public final int Hours()
{
boolean canceled = false;
for (int index = 0; index < name.length; index++) {
JOptionPane.shoeMessageDialog(“Please enter " + name[index] + “’s hours”);
for (int x = 0; x <= hours.length; x++)
for (int y = 0; y <= hours[x].length; y++)
Integer value = promptForInt(artist[index] + “’s first hour: ”);
if (value != null) {
while (value < 0)
{
JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
value = promptForInt(name[index] + “’s first hour: ”);
}
pay[x][y] = value;
} else {
canceled = true;
break;
}
}
public static void main(String[] args) // Main program
{
for (int x = 0; x <= name.length; x++)
for (int y = 0; y <= hours.length; y++)
System.out.println(x, y);
}

Try adding in brackets like so:
import javax.swing.JOptionPane;
public class Gain
{
// Defining array names.
String[] name = {"A", “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “L”};
int[][] hours = new int[10][3];
public final int Hours()
{
boolean canceled = false;
for (int index = 0; index < name.length; index++)
{
JOptionPane.shoeMessageDialog("Please enter " + name[index] + "’s hours");
for (int x = 0; x <= hours.length; x++)
{
for (int y = 0; y <= hours[x].length; y++)
{
Integer value = promptForInt(artist[index] + “’s first hour: ”);
if (value != null)
{
while (value < 0)
{
JOptionPane.showMessageDialog(null, "Please positive figures." + "\nPlease try again.");
value = promptForInt(name[index] + “’s first hour: ”);
}
pay[x][y] = value;
}
else
{
canceled = true;
break;
}
}
}
}
}
public static void main(String[] args) // Main program
{
for (int x = 0; x <= name.length; x++)
for (int y = 0; y <= hours.length; y++)
System.out.println(x, y);
}
While it's fine to avoid brackets in a for loop when you only have one line of code afterwards (like in your main method), you need to use them when you have a whole block, as is the case here in your Hours() method. Personally, I like to use brackets all of the time as it makes the code more readable, but that's just me. :)

Related

Bad operand types for binary operator '>' using doubles

So I get the error in the findSmallest and findLargest methods, but I understand the error, I just don't understand why it is happening. I am comparing 2 doubles in a 2D array, but it is still telling me I can't compare them with a '>'. Any help would be greatly appreciated. You can skip over most of the main method to the places where I have the problems.
import java.util.Scanner;
public class DivingScores
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[] judge = new String[7]; //
System.out.println("Enter judges' names:"); //
for(int x = 0; x<judge.length; x++) //
judge[x] = input.nextLine(); //
//
String[] diver = new String[4]; //
System.out.println("Enter divers' names:"); //
for(int x = 0; x<diver.length; x++) //
diver[x] = input.nextLine(); // Creating and Instantiating
//
double[] diveDifficulty = new double[7]; //
for(int x = 0; x<diveDifficulty.length; x++) //
diveDifficulty[x] = input.nextDouble(); //
//
double[][] diverScore = new double[4][7]; //
for(int x = 0; x<diverScore.length; x++) //
for(int y = 0; y<diverScore[x].length; y++) //
diverScore[x][y] = input.nextDouble(); //
System.out.println("Judges"); //
for(int x = 0; x<judge.length; x++) //
System.out.printf("%15s, ", judge[x]); //
System.out.println(); //
//
System.out.println("Divers"); //
for(int x = 0; x<diver.length; x++) //
System.out.printf("%13s, ",diver[x]); //
System.out.println(); //
//
System.out.println("Dive Difficulty"); // Printing
for(int x = 0; x<diveDifficulty.length; x++) //
System.out.printf("%2.2f, ", diveDifficulty[x]); //
System.out.println(); //
//
System.out.println("Diver Scores"); //
for(int x = 0; x<diverScore.length; x++) //
{ //
System.out.println(diver[x]); //
for(int y = 0; y<diverScore[x].length; y++) //
System.out.printf("%2.2f ", diverScore[x][y]); //
System.out.println(); //
}
findSmallest(diverScore);
findLargest(diverScore);
awardMedal(calcScore(diverScore, diveDifficulty, diver.length), diver);
}
public static void findSmallest(double[][] diverScore)
{
for(int x = 0; x<diverScore.length; x++)
{
int smallest = 0;
for(int y = 0; y<diverScore[x].length; y++)
{
if(y > 0 && diverScore[smallest] > diverScore[y]) //Error Here
smallest=y;
}
diverScore[x][smallest] = 0;
}
}
public static void findLargest(double[][] diverScore)
{
for(int x = 0; x<diverScore.length; x++)
{
int largest = 0;
for(int y = 0; y<diverScore[x].length; y++)
{
if(y > 0 && diverScore[largest] < diverScore[y]) //Error Here
largest=y;
}
diverScore[x][largest] = 0;
}
}
public static double[] calcScore(double[][] diverScore, double[] diveDifficulty, int divers)
{
double[] scores = new double[divers];
for(int x=0; x<divers; x++)
{
double total = 0;
for(int y=0;y<diverScore[x].length;y++)
total += diverScore[x][y]*diveDifficulty[y];
scores[x]=total;
}
return scores;
}
public static void awardMedal(double[] scores, String[] diver)
{
int first = 0;
int second = 0;
int third = 0;
for(int x = 0; x<scores.length; x++)
{
if(x!=0 && scores[first]<scores[x])
first = x;
}
System.out.println(diver[first] + scores[first] + " Gold");
scores[first]=0;
for(int x = 0; x<scores.length; x++)
{
if(x!=0 && scores[second]<scores[x])
second = x;
}
System.out.println(diver[second] + scores[second] + " Silver");
scores[second]=0;
for(int x = 0; x<scores.length; x++)
{
if(x!=0 && scores[third]<scores[x])
third = x;
}
System.out.println(diver[third] + scores[third] + " Bronze");
}
}
I have no idea why the error is occurring in this case but is there an alternative way to do what I have done?
it is a 2D array, so when you are doing
diverScore[smallest] > diverScore[y]
you are comparing Arrays not doubles.
double[][] diverScore
As per your input
for(int x = 0; x<diverScore.length; x++) //
for(int y = 0; y<diverScore[x].length; y++) //
// here
You need to do an inner loop

Showing Multiple Variables in Console with Scanner

The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}

Java Search array for number

I have a project where I need to search an array of 50 elements and not only print those elements, which is figured out, but I need to find a number, boolean check = false, say 10 and if I do print a message box that I found it!
import java.util.*;
public class IT145_Homework_5_4 {
public static void main(String args[]) {
double alpha[] = new double[50];
boolean check = false;
// Initialize the first 25 elements of the array (int i=0; i<25; i++)
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
// Initialize the last 25 elements of the array (i=25; i<50; i++)
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
// Print the element of the array
System.out.println("The values are: ");
print(alpha);
}
// Print method to display the element of the array
private static void print(double m_array[]) {
for (int i = 1; i <= m_array.length; i++) {
System.out.print(m_array[i - 1] + " ");
if (i % 10 == 0)
System.out.print("\n");
}
}
}
public class IT145_Homework_5_4
{
public static void main(String args[])
{
double alpha[] = new double[50]; // all the values are whole numbers, why not make them of type int?
// Initialize the first 25 elements of the array (int i=0; i<25; i++)
for (int i = 0; i < 25; i++)
alpha[i] = i * i;
// Initialize the last 25 elements of the array (i=25; i<50; i++)
for (int i = 25; i < 50; i++)
alpha[i] = 3 * i;
// Print the element of the array
System.out.println("The values are: ");
print(alpha);
// Searches for value in array
double valueToFind = 100;
if(find(alpha, valueToFind))
System.out.println(valueToFind + " is in the array");
else
System.out.println(valueToFind + " is not in the array");
}
// Print method to display the element of the array
private static void print(double m_array[])
{
for (int i = 1; i <= m_array.length; i++)
{
System.out.print(m_array[i - 1] + "\t\t");
if (i % 10 == 0)
System.out.print("\n");
}
}
//Method to find element in array
private static boolean find(double m_array[], double valueToFind)
{
for(int i = 0; i < m_array.length; i++) //remember that arrays start with index 0
if(m_array[i] == valueToFind)
return true;
return false;
}
}
private static void print(double m_array[]) {
boolean check = false;
int result = 0;
for (int i = 1; i <= m_array.length; i++) {
System.out.print(m_array[i - 1] + " ");
if (i % 10 == 0)
System.out.print("\n");
if(m_array[i-1] == 10){
result = m_array[i - 1];
check = true;
}
}
if(check){
//Print message box with value stored in "result" variable
}
}

Problems Sorting a two column array and outputting value frequency in Java

Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}

What can I do to get rid of the nullpointer exception in this program?

package program2;
import java.util.*;
import java.io.*;
import java.io.CharArrayReader;
public class Program2 {
public static void main(String[] args) {
try {
String filename = args[0]; //reads command line argument 1 as filename
Scanner File = new Scanner(new File(filename)); //reads filename into program,and opens it for analysis
File.useDelimiter(System.getProperty("line.seperator"));
ArrayList<String> list = new ArrayList<>(); //creates an array list to store chars to transfer for reading from the file
while (File.hasNext()) {
list.add(File.next()); //adds each char letter to the list
}
File.close();//closes file stream
char[][] array1 = new char[10][20];
for (int i = 0; i < list.size(); i++) {
array1[i] = list.get(i).toCharArray(); //converts array list -> char array
}
int[] CountA = new int[200];
CountA = CharSearch(array1, 'A');
int[] CountB = new int[200];
CountB = CharSearch(array1, 'B');
int[] CountC = new int[200];
CountC = CharSearch(array1, 'C');
int totalA = 0;
int totalB = 0;
int totalC = 0;
int totalgroupsA = 0;
int totalgroupsB = 0;
int totalgroupsC = 0;
for (int i = 0; i > CountA.length; i++) {
if (CountA[i] != 0) {
totalA += CountA[i];
totalgroupsA++;
}
}
for (int i = 0; i > CountB.length; i++) {
if (CountB[i] != 0) {
totalB += CountB[i];
totalgroupsB++;
}
}
for (int i = 0; i > CountC.length; i++) {
if (CountC[i] != 0) {
totalC += CountC[i];
totalgroupsC++;
}
}
System.out.println(filename);
for (int i = 0; i> array1.length; i++){
for (int j = 0; j> array1.length; j++){
System.out.println(array1[i][j]);
if (array1[i][j] == array1[i][20])
System.out.println("\n");
}
}
System.out.println();
System.out.println("The number of groups of A is: " + totalgroupsA);
System.out.println("The number of groups of B is: " + totalgroupsB);
System.out.println("The number of groups of C is: " + totalgroupsC);
if (totalA > totalB && totalA > totalC) {
System.out.println("The largest group is " + totalA);
} else if (totalB > totalA && totalB > totalC) {
System.out.println("The largest group is " + totalB);
} else if (totalC > totalB && totalC > totalA) {
System.out.println("The largest group is " + totalC);
}
} catch (FileNotFoundException e) {
System.out.println("File is not found: " + e.getMessage());//catches and sends out an error message
}
}
static int[] CharSearch(char[][] array1, char a) {
int w = 10;
int h = 20;
int[] rst = new int[w * h];
int count = 0;
int next_region = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1.length; j++) {
if (array1[i][j] == a) {
continue;
}
count += 1;
int k = 0;
boolean connected = false;
//if connected to the left
if (j > 0 && array1[i][j - 1] == array1[i][j]) {
count += 1;
connected = true;
}
//if connected upwards
if (i > 0 && array1[i - 1][j] == array1[i][j] && (connected = false)) {
count += 1;
connected = true;
}
if (!connected) {
k = next_region;
rst[k] = count;
next_region++;
}
}
}
return rst;
}}
So I am getting a nullpointerexception and I wanna know where in my program there is a nullpointer exception? I tried switching stuff over to make more sense but it still doesn't work... Please help. There are of course a couple of more things that it says:
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Pattern.<init>(Pattern.java:1336)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at java.util.Scanner$1.create(Scanner.java:411)
at java.util.Scanner$1.create(Scanner.java:409)
at sun.misc.LRUCache.forName(LRUCache.java:70)
at java.util.Scanner.useDelimiter(Scanner.java:1195)
at program2.Program2.main(Program2.java:13)
Your NullPointerException originates from this line:
File.useDelimiter(System.getProperty("line.seperator"));
Note you have a typo in the word "seperator" - it's supposed to be "separator" (a after the p). Because of this typo, you're trying to get property that doesn't exist, which returns null. Then, you use this value in File.userDelimiter, which expects a not-null value, and fails with the aforementioned exception.
These are the key lines in the stack trace:
at java.util.Scanner.useDelimiter(Scanner.java:1195)
at program2.Program2.main(Program2.java:13)
The program failed at line 13 in Program2. From what you posted, it looks like line 13 is this:
File.useDelimiter(System.getProperty("line.seperator"));
Which then corresponds to the next error - useDelimiter is failing. What is the value you are passing into this method? Are you sure it's non-null, and valid input for the useDelimiter method? What is System.getProperty("line.seperator") returning?
Note: seperator is a typo - the word is actually separator

Categories

Resources