The first line contains a single integer p denoting the length of array. The second line contains space-separated integers describing each respective element in array. The third line prints an integer indicating the number of negative arrays.
package asgn3;
import java.util.*;
public class Asgn3 {
public static void main(String[] args) {
int count = 0, result = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the array ");
String s = in.nextLine();
int j = 0;
String[] s1 = s.split(" ");
int a[] = new int[s1.length];
for(String s2:s1) {
a[j] = Integer.parseInt(s2));
j++;
}
for (int i = 0; i < a.length; i++) {
for ( j = i; j < a.length; j ++) {
for (int k = i; k <= j; k++) {
result += a[k];
}
if(result < 0)
count ++;
}
System.out.println("no. of negatve arrays is "+count);
}
}
}
The issues is usage of extra unnecessary parenthesis. Change,
a[j]=Integer.parseInt(s2));
with
a[j]=Integer.parseInt(s2);
Remove extra bracket ) from end of line
a[j] = Integer.parseInt(s2);
Related
I want to write a code which can sort char array element. But the problem is where i want to sort 'a' before 'aa' element and I don't know how to write this part. It always sort 'aa' before 'a'. At first it get inputs from user and if we write '0' it will print sorted array.
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
You have to consider that 'aa' is not a char, instead 'a' is a char.
If you want to sort strings the code is nearly okay.
Here an example:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int num = 0;
String[] arr = new String[1000];
String index = "";
Scanner myObj = new Scanner(System.in);
for(int i = 0; i < 1000; i++){
arr[i] = myObj.nextLine();
if(arr[i].equals("0")){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i].compareTo(arr[j]) < 0){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
System.out.print("[ ");
for(int i = 0; i < num; i++){
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
Input:
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0
Expected Output:
[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
It is only sorting by the first char of an entered word.
Thus it seems like the input-order is preserved.
Issue
Adding some debug-prints shows the comparison of first-char is leading to incorrect or unwanted aa before a case:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
System.out.printf("Debug [%d]: '%s' \n", i, String.valueOf(arr[i]));
for(int j = 0; j < i; j++){
System.out.printf("Compare '%s' < '%s' = %s\n", arr[i][0], arr[j][0], (arr[i][0] < arr[j][0]));
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
Output:
a
Debug [0]: 'a'
aa
Debug [1]: 'aa'
Compare 'a' < 'a' = false
0
a
aa
Refactored and solved
I just added a bit output to interact with user.
Also refactored a bit (extract into methods, and control length of arrays with a configurable constant).
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner myObj = new Scanner(System.in);
public static void main(String[] args) {
char[][] arr = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int num = readArray(0, arr);
System.out.printf("Printing %d elements:\n", num);
printArray(num, arr);
}
private static int readArray(int num, char[][] arr) {
char[] index;
int i;
for (i = 0; i < LENGTH; i++) {
arr[i] = readChars();
if (arr[i][0] == '0') {
break;
} else {
num++;
}
for (int j = 0; j < i; j++) {
if (String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
return num;
}
private static void printArray(int num, char[][] arr) {
int i;
for (i = 0; i < num; i++) {
System.out.println(arr[i]);
}
}
private static char[] readChars() {
return myObj.next().toCharArray();
}
}
Output is as expected (a before aa):
Enter elements (each on a new line, 0 stops):
z
aa
b
a
0
Printing 4 elements:
a
aa
b
z
How it works
Entire array compared (chars in sequence) instead only the first char of each array.
before:
arr[i][0] < arr[j][0]
after:
String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0
Bonus Tip: Naming can help to spot logical bugs
When renaming the methods and variable names it may get a bit clearer what the program does, we call it semantics:
myObj becomes scanner
i becomes index or wordIndex or lineIndex and lastLineIndex
j is actually a character-index ... but in this short scope it should can be self-evident
char-arrays can be lines or words
num becomes length of lines or countLines
and all the method-names are adjusted in semantics to operate on lines, expressed by name <verb>Lines
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] lines = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int countLines = readLines(lines);
System.out.printf("Printing %d elements:\n", countLines);
printLines(lines, countLines);
}
private static int readLines(char[][] lines) {
int linesRead = 0;
for (int lineIndex = 0; lineIndex < LENGTH; lineIndex++) {
lines[lineIndex] = readLine();
if (lines[lineIndex][0] == '0') {
break;
} else {
linesRead++;
}
sortLines(lines, lineIndex);
}
return linesRead;
}
private static void sortLines(char[][] lines, int lastLineIndex) {
for (int j = 0; j < lastLineIndex; j++) {
if (String.valueOf(lines[lastLineIndex]).compareTo(String.valueOf(lines[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
char[] line = lines[lastLineIndex];
lines[lastLineIndex] = lines[j];
lines[j] = line;
j = 0;
}
}
}
private static void printLines(char[][] lines, int length) {
for (int i = 0; i < length; i++) {
System.out.println(lines[i]);
}
}
private static char[] readLine() {
return scanner.next().toCharArray();
}
}
My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}
I was writing the code for the least occurring element in the array and for some reason my logic goes wrong and the compiler just prints either the first or the second element in the array? anyone know what's wrong?
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
count = 0;
}
}
System.out.print(store);
}
}
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
static int leastFrequent(int arr[], int n)
// n is length of array
{
// Sort the array
Arrays.sort(arr);
// find the min frequency using
// linear traversal
int min_count = n+1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count < min_count) {
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
I guess you are trying to implement the following logic
Find the count of each element in the array
If you find an element with lower count - store the element
Repeat for each element in the array - to find the lowest element.
You should have rest the count at the end of the inner loop as,
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
}
count = 0;
}
System.out.print(store);
}
}
You have a single counter, so you'll lose this counting once you transition from one element to another.
You could hold an auxiliary map of counters and update it as you go, but frankly, using Java's streams will save you a lot of boilerplate code:
int leastOccuring =
Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())
.entrySet()
.stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::geyKey)
.get();
This would be the correct code for your program.
import java.util.*;
public class LeastOccuringElementInArray {
public static void main(String[] args) {
int m = 0;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++)
{
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++)
{ c = a[i] ;
for(int j =0; j <n ; j++)
{
if(a[j] == c)
{
count++ ;
}
if(j == (n-1))
{
if(m!=0 && m > count)
{
store = a[i];
m = count;
}
else {
m = count;
}
}
}
count = 0;
}
System.out.print(store);
scan.close();
}
}
I am trying to print the non repeated values when user enter some numbers it should display the numbers which are not duplicate. i am getting all the values and my program is as below
public class Compare {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the string:");
int[] array = new int[7];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(sc.nextLine());
}
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = i+1; j < array.length; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if(!found)
System.out.println(array[i]);
}
}
}
Instead of boolean found, take a int count=0 for counting the numbers and print the numbers which have count == 1
Change the code accordingly as shown
for (int i = 0; i < array.length; i++) {
int count=0;
for (int j = 0; j < array.length; j++)
if (array[i] == array[j]) {
count++;
}
if(count==1)
System.out.println(array[i]);
}
Input:
1
2
2
3
3
4
5
Output:
1
4
5
You only have to change two things:
Check the whole array for duplicates. int j = 0 instead of int j = i
Don't compare the the value with itself. Add && i != j to your if condition.
Now your code will work.
Input: 1,2,3,3,4,5,6
Output: 1,2,4,5,6
How about using, HashSet?
It will only contain non duplicate values.
You could do this quicker with a map counting the number of values:
public class Compare {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the string:");
Map<int, int> values = new HashMap<int, int>();
for (int i=0; i<7;i++) {
value = Integer.parseInt(sc.nextLine());
if (!values.contains(value)) {
values.put(value, 1);
} else {
values.put(value, values.get(value) + 1);
}
}
for (int value : values.keySet()) {
if (values.get(value) == 1) {
System.out.println(value);
}
}
}
}
When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.