I have it go through an array and assign values to it from an arraylist. I'm having trouble with trying to write a thing that can see if there are enough rows and columns for a set value in the arraylist names. everytime it prints it just prints as one line and not as row and columns with the respective numbers. I don't know what I'm doing wrong.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class SeatingChart {
public static void main(String[] args) {
// instanced variables
Scanner kb = new Scanner(System.in);
String name = "";
int r = 0;
int c = 0;
int k = 0;
String row = "";
String column = "";
ArrayList<String> names = new ArrayList<String>();
while (!name.equals("quit")) {
System.out.print("Enter first name of student: ");
// takes the name of kb and sets it to name
name = kb.nextLine();
// if the ArrayList names isEmpty then it adds the value at index
if (names.isEmpty()) {
names.add(name);
} else if (name.compareTo(names.get(names.size() - 1)) > 0) {
names.add(name);
} else {
// for loop going through the list of names to insert where it belongs
for (int i = 0; i < names.size(); i++) {
if (name.compareTo(names.get(i)) < 0) {
names.add(i, name);
i = names.size();
}
}
}
if (names.contains("quit")) {
names.remove("quit");
}
}
System.out.println(names);
// System.out.println(names);
System.out.println("how many rows do you have: ");
r = kb.nextInt();
System.out.println();
System.out.println("how many columns do you have: ");
c = kb.nextInt();
System.out.println();
System.out.println("Should students be seated row major(1) or column major(0)?");
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
}
} else if (kb.nextInt() == 2) {
String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < names.size(); i++) {
arr[i] = names.get(i);
}
System.out.println(Arrays.toString(arr));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
arr[i] = chart[r][c];
k++;
}
}
for (int i = 0; i < chart[0].length; i++) {
for (int j = 0; j < chart.length; j++) {
System.out.printf("%10s ", chart[i][j]);
}
}
System.out.println("Column order!");
}
}
}
I have fixed one IF Block for major
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
System.out.println(""); // ADD THIS
}
}
Related
I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);
I have a two dimensional array and I fill it with scanner. I want to copy the elements that start with letter 'a' to a new one dimensional array without using ArrayList. Please advise on what I can do to get this code functioning properly. the question is how can I know the new array size while I don't know how many words start with letter a
Here is what I have so far:
import java.util.Scanner;
class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int c2 = -1;
String[] name2 = new String[count];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
c2++;
temp = arr[i][j];
name2[c2] = temp;
count++;
temp = "";
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
}
}
A two dimensional arrray of size [n][n] is equal to one dimensional array of size n. If you want to copy them on proper place then you can use this formula, it is useful if you later want to copy these elements back to twodimensional array at proper places:
int v = i * n + j; // i and j your loops and n is length of rows or colums.
array[v] = array[i][j];
for in your codes it's like:
int v = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i * arra.length +j;
name2[v] = arr[i][j];
count++;
Ok here is a working code:
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
System.out.println("Enter the name: ");
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int v = 0;
String[] name2 = new String[arr.length*arr[0].length];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i *+arr[0].length + j;
name2[v] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
System.out.println("printing without nulls");
//if you don't want null to be printed then do this:
for (int i = 0; i < name2.length; i++) {
if(name2[i] != null)
System.out.println(name2[i]);
}
}
I did it with two nested for loop one for indicating the array size and the other for filling the elements into the array, it does the work but is there any way to do this better
public static void student(String[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
size++;
}
}//inner
}//outer
String[] name2 = new String[size];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
name2[count] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};
I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}
Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
public void sortedArrayByRowTot() {
int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
int [] rowSums = new int [tempArray2.length];
int sum = 0;
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
sum += tempArray2[i][j];
}
rowSums[i] = sum;
sum = 0;
}
int temp;
int i = -1;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
}
}
if(!isSwap){
break;
}
}
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
}
Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"
As #shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
}
Input:
abc
def
feg
cba
This is what I am doing, of course wrong!
import java.util.Scanner;
public class P {
public static void main(String []args){
Scanner x = new Scanner(System.in);
int t = x.nextInt();
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
for (j=0; j<p.length(); j++) {
for (k=0; k<p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
}
}
}
}
The error message you wrote is because of this code:
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
If you want to create a String array this is how you do it:
String[] p = new String[t];
It also needs to be declared outside of your for-loop. I suggest something like this:
public static void main(String []args){
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String[] p = new String[t];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (j=0; j<p.length(); j++) {
...
}
}
The new code you posted:
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String p[] = new String[n];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (j = 0; j < p.length(); j++) {
for(k = 1; k < p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
With all the corrections I've commented your code should look like this:
Scanner x = new Scanner(System.in);
int t = x.nextInt();
String[] p = new String[t];
for (int j = 0; j < t; j++) {
p[j] = x.nextLine();
}
for (int j = 0; j < p.length(); j++) {
for (int k = 1; k < p.length(); k++) {
if (p[j] = reverse(p[k])) {
int q = p[k].length();
System.out.println("" + q + ((q / 2) + 1));
}
}
}
at a glance, it seems like your scoping is off. The variable p in
for (int j=0; j<t; j++) {
String p[j] = x.nextLine();
}
is declared and then immediately discarded. You probably want something more like
String[] p = new String[t];
for (int j=0; j<t; j++) {
p[j] = x.nextLine();
}
similarly with q in the loop below
int q = 0;
for (int j=0; j<p.length; j++) {
for (int k=0; k<p.length; k++) {
if (p[j] = reverse(p[k])) {
q = p[k].length();
System.out.println(""+q+((q/2)+1));
}
}
}
Hope this helped.
more information about variable scope in Java:
variable scope
So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut