How to read values into 2 dimensional array in java - java

5
1,0,1,1,1
1,1,1,1,1
0,0,0,1,1
0,1,0,1,0
1,0,0,1,1
I am trying to store the above values into 2-d array. My code is for this problem is given below. I don't know why it doesn't stores the values.
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
System.out.println(n);
String[][] multi = new String[n][n];
int i=0;
int t=n;
while(t>0){
String s=scan.nextLine();
String b[]=s.split(",");
for(int j=0;j<b.length;j++){
//System.out.print(b[j]+" ");
multi[i][j]=b[j];
}
//System.out.println();
i++;
t--;
}
System.out.println(multi[0][0]);
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
System.out.println();
}
}
}
But it doesn't stores.Can any one help me to solve my problem.
Tell me how to do this.

Change
> for(int k=0;i<n;i++)
to
> for(int k=0;k<n;k++)
EDIT:
Change final for loop to:
for(int k=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
And your final code looks like:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i=0;
int t=0;
while(t<n){
String s=scan.nextLine();
String b[]=s.split("\\,");
for(int j=0;j<b.length;j++){
multi[i][j]=b[j];
}
i++;
t++;
}
System.out.println(multi[0][0]);
for(int k=0;k<n;k++){
for(int j=0;j<n;j++){
System.out.print(multi[k][j]+" ");
}
System.out.println();
}
}
Good Luck.

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String[][] multi = new String[n][n];
int i = 0;
int t = n;
while (t > 0) {
String s = scan.nextLine();
String b[] = s.split(",");
for (int j = 0; j < b.length; j++) {
multi[i][j] = b[j];
}
i++;
t--;
}
for (int k = 0; k < n; k++) {
for (int j = 0; j < n; j++) {
System.out.print(multi[k][j] + " ");
System.out.println();
}
}
}

Please replace
int n=scan.nextInt()
by int n=scan.nextLine()

Related

TLE error in my code to count how many duplicate elements are there in an array! What's Wrong in my code?

I want to count the number of duplicate elements in an array. My code works fine in my Compiler but when I try to submit my code it shows TLE(Time Limit Exceeded) Error. My code is here:
public static void main(String[] args) throws IOException {
Scanner s= new Scanner(System.in);
long count=0;
long n=s.nextLong();
for(int i=0; i<n; i++) {
int g=s.nextInt();
int []arr=new int [g];
for(int j=0; j<g; j++) {
arr[j]=s.nextInt();
}
for(int j=0; j<g; j++) {
for(int k=j+1; k<g; k++) {
if(arr[j]==arr[k]) {
count++;
}
}
}
System.out.println(count);
count=0;
}
}
}
run this code it perfectly works
you asked for some extra value which is not needed
public static void main(String[] args){
Scanner s= new Scanner(System.in);
long count=0;
//long n=s.nextLong(); // there is NO NEED for this line !
//for(int i=0; i<n; i++) { // there is NO NEED for this line !
int g=s.nextInt();
int []arr=new int [g];
for(int j=0; j<g; j++) {
arr[j]=s.nextInt();
}
for(int j=0; j<g; j++) {
for(int k=j+1; k<g; k++) {
if(arr[j]==arr[k]) {
count++;
}
}
}
System.out.println(count);
count=0;
//} // there is NO NEED for this line !
}

Sorting an array in a decreasing order in Java

I'm trying to code a program that will sort the given strings one by one first and then sorting all the strings both in decreasing order I managed to sort the string character by character but I am having trouble in sorting all the sorted (character by character) strings. I tried using the Array.sort() but it does not sort it decreasingly and it only sorts the first input not the already sorted array
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void sortString(String str)
{
char[] chArr = str.toCharArray();
String SortString = "";
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j< chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
String[] SortedString = new String[5];
for (int k = 0; k<chArr.length;k++)
{
SortString = SortString + chArr[k];
}
Arrays.sort(SortedString);
for (int counter = 0; counter<5; counter++)
{
System.out.println(SortedString[counter]);
}
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
UserInput.close();
Arrays.sort(names);
for (int counter = 0; counter<5; counter++)
{
sortString(names[counter]);
}
}
}
static String sortString(String str)
{
char[] chArr = str.toCharArray();
for (int i = 0; i< chArr.length; i++)
{
for (int j = 0; j< chArr.length; j++)
{
if(chArr[i] > chArr[j])
{
char temp = chArr[i];
chArr[i] = chArr[j];
chArr[j] = temp;
}
}
}
return new String(chArr);
}
public static void main(String[] args)
{
Scanner UserInput = new Scanner (System.in);
String[] names = new String[5];
for (int counter = 0; counter<5; counter++)
{
do
{
System.out.print("Input String #" + (counter+1) + ": ") ;
names[counter] = UserInput.next().toLowerCase();
}while(names[counter].length() > 25);
}
UserInput.close();
// Arrays.sort(names); No point sorting here
String[] strings = new String[5];
for (int counter = 0; counter<5; counter++)
{
strings[counter] = sortString(names[counter]);
}
Arrays.sort(strings);
// increasing order:
for(String s : strings) {
System.out.println(s);
}
// decreasing order:
for(int i = 4; i >= 0; i--) {
System.out.println(strings[i]);
}
}

how to insert in two dimensional array?

i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}

Removing NullPointerException in Java

public class leftrec {
static int isleft(String[] left,String[] right)
{
int f=0;
for(int i=0;i<left.length;i++)
{
for(int j=0;j<right.length;j++)
{
if(left[i].charAt(0)==right[j].charAt(0))
{
System.out.println("Grammar is left recursive");
f=1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
String[] left=new String[10];
String[] right=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("enter no of prod");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
System.out.println("the productions are");
for(int i=0;i<n;i++)
{
System.out.println(left[i]+"->"+right[i]);
}
int flag=0;
flag=isleft(left,right);
if(flag==1)
{
System.out.println("Removing left recursion");
}
else
{
System.out.println("No left recursion");
}
}
}
I've written this code to find out if the given grammar is left recursive or not. When i compile the program it gives me NullPointerException in lines
if(left[i].charAt(0)==right[j].charAt(0))
and
isleft(left,right);
How do i remove the exception ?
I Guess the problem with your inputs , You are just taking the String Array lengths as 10.
String[] left=new String[10];
String[] right=new String[10];
Dont HardCode the String Array length
int n=sc.nextInt();
String[] left=new String[n];
String[] right=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter left prod");
left[i]=sc.next();
System.out.println("enter right prod");
right[i]=sc.next();
}
Might ,this would be the problem
You need to change the code as follows::
package com.cgi.ie2.common;
import java.util.Scanner;
public class LeftRecursive {
static int isleft(String[] left, String[] right)
{
int f = 0;
for (int i = 0; i < left.length; i++) {
for (int j = 0; j < right.length; j++)
{
if (left[i].charAt(0) == right[j].charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
left[i] = sc.next();
System.out.println("enter right prod");
right[i] = sc.next();
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left[i] + "->" + right[i]);
}
int flag = 0;
flag = isleft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
}
This code will eliminate the NullpointerExceptions
If you getting the no. of prod from the console, the String arrays need to set accordingly,for that the changes i have done are::
System.out.println("enter no of prod");
int n = sc.nextInt();
//Changes done here::::
String[] left = new String[n];
String[] right = new String[n];
And for better codes what i can suggest you is you need to follow basic coding conventions,which makes your codes readable,codes are not perfect only if it runs corectly,codes are perfect if a coding conventions are follow,so please go through the following links to undestand basic idea of coding conventions::
http://www.javacodegeeks.com/2012/10/java-coding-conventions-considered-harmful.html
http://java.about.com/od/javasyntax/a/nameconventions.htm
you can`t initialize an array without size. You have already given the array sizes as 10 and if you enter products which bigger than 10 or smaller than 10 you will get errors. There fore if you want to use dynamic size , you should use a java collection. best approach for this is array list
static int isLeft(ArrayList left, ArrayList right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}

Sort strings in an array based on length

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}

Categories

Resources