java display method - java

Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}

import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}

You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!

Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true

i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}

Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}

Related

What is my error in making method to call an array?

My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}

Clearing and array and filling it with zeros

I am creating an double array called MySize that will hold user input.
How do I clear an array, by filling it in with all zero using an if statement?
I tried creating a function called ClearMySize to allow the user to clear the entire array that they created and fill it full of zeros
package trashmysize;
import java.util.Arrays;
import java.util.Scanner;
public class TrashMySize {
static double [][] MySize;
static int b1 = 0;
static int b2 = 0;
static Scanner scanSize = new Scanner(System.in);
static int columns = 0;
static int rows = 0;
static int NumberOfElements;
static void PrintMySize(){
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print(MySize[r][c] + " ");
}
System.out.println();
}
}
static void BuildMySize(){
System.out.println("Enter the number of columns: ");
rows = Integer.parseInt(scanSize.nextLine());
System.out.println("Enter the number of rows: ");
columns = Integer.parseInt(scanSize.nextLine());
MySize = new double[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
System.out.print(MySize[r][c] + " ");
}
System.out.println();
}
Menu();
}
static void UserEntryMySize(){
int blue = 0;
double value = 0;
while(blue < 1){
System.out.println("Enter value: ");
value = Double.parseDouble(scanSize.nextLine());
System.out.println("What row: ");
b1 = Integer.parseInt(scanSize.nextLine()) -1;
System.out.println("What column: ");
b2 = Integer.parseInt(scanSize.nextLine()) -1;
try{
if(b1 <= rows-1 && b2 <= columns-1){
System.out.println("Good position");
}
blue++;
}
catch(Exception e){
System.out.println(e.getMessage());
System.out.println("Not a good position");
blue++;
BuildMySize();
}
}
MySize[b1][b2] = value;
PrintMySize();
Menu();
}
static void ClearMySize(){
if(MySize != null){
//for (int i = 0; i < MySize.length; i++)
//MySize[i] = 0;
Arrays.fill(MySize, 0);
} else {
System.out.println("Array is empty");
}
System.out.println("\nArray has been cleared: " + Arrays.toString(MySize));
PrintMySize();
Menu();
}
static public void Menu(){
int choice = 0;
Scanner myScan = new Scanner(System.in);
System.out.println("\nMain Menu\n"
+ "\n1. Build MySize"
+ "\n2. Add to MySize"
+ "\n3. Clear MySize"
+ "\nMake a choice: ");
choice = Integer.parseInt(myScan.nextLine());
switch(choice){
case 1 -> BuildMySize();
case 2 -> UserEntryMySize();
case 3 -> ClearMySize();
case 4 -> Menu();
case 5 -> {
System.out.println("Thank you for playing! Have a good day!");
System.exit(0);
}
}
}
public static void main(String[] args) {
Menu();
}
}
But that doesn't work. It just seems to crash my code.
I keep getting the error message of:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at java.base/java.util.Arrays.fill(Arrays.java:3429)
at trashmysize.TrashMySize.ClearMySize(TrashMySize.java:107)
at trashmysize.TrashMySize.Menu(TrashMySize.java:136)
at trashmysize.TrashMySize.UserEntryMySize(TrashMySize.java:91)
at trashmysize.TrashMySize.Menu(TrashMySize.java:135)
at trashmysize.TrashMySize.BuildMySize(TrashMySize.java:51)
at trashmysize.TrashMySize.Menu(TrashMySize.java:134)
at trashmysize.TrashMySize.main(TrashMySize.java:145)
C:\Users\Amanda\Documents\NetBeansProjects\trashMySize\nbproject\build-impl.xml:1330: The following error occurred while executing this line:
C:\Users\Amanda\Documents\NetBeansProjects\trashMySize\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 15 seconds)
Everything works as it should except for my clear function.
Well the easiest solution is:
if(condition)
{
for(int i=0; i<array.length; i++)
{
array[i] = 0
}
}
Is this what you're looking for?
Iterate through all indexes and set values to 0.
if(array != null){
for(int i=0;i<array.length;i++) array[i] = 0;
}
OK, so this is more complicated than the other answers have realized.
The first thing to note is that this is not an simple array. The array is declared as a:
static double [][] MySize;
That is an array of arrays.
(And really seriously, that is an awful choice that you have made for the array variable name. It bears no relation to what the variable means, and it is a major Java style violation to boot.)
You try to fill it like this:
Arrays.fill(MySize, 0);
So now we look at the overloads for Arrays.fill and we see that there are three overloads that might be relevant:
Arrays.fill(int[], int); #1
Arrays.fill(double[], double); #2
Arrays.fill(Object[], Object); #3
The first one does not apply because double[][] is not compatible with int[] (though the 2nd argument matches exactly).
The second one does not apply because double[][] is not compatible with double[]. (The second argument is compatible by a primitive widening conversion.)
The third one does apply because double[][] IS compatible with Object[], because double[] is a subtype of Object. However, for that to "work", the Object you are supplying as the 2nd argument needs to be a double[]. It it isn't. It is an int. And Java is performing a boxing conversion to turn that into a Integer ... 'cos that is what the JLS says it should do.
So as a result, fill will attempt to assign an Integer into a cell of an array double[] ... which throws an exception.
Lesson #1. Be careful with multi-dimensional array types in Java. They are not entirely intuitive.
Lesson #2. Only use Array.fill(...) for 1D arrays.
The actual solution here is this:
for (double[] d: MySize) {
Arrays.fill(d, 0.0);
}
or you could you could use a nested for loop and do the filling by hand.

Check for duplication of number in ArrayList - Java

I'm currently making a sudoku program, however my current code seems to fail me. The script below should put out a print "Inconsistent sudoku puzzle" if a row contains the same number several times, but sadly it doesn't.. I've tried several different attempts but no succes.
public void checkRow() {
int count = 0;
for(int j = 0; j < list.size(); j++) {
for(int a = 1; a < 10; a++) {
for (int i=0; i < list.get(j).length(); i++) {
if(list.get(j).charAt(i) == a) {
count++;
if(count >= 2) {
System.out.println("Inconsistent sudoku puzzle");
count = 0;
}
}
}
count = 0;
}
}
}
This is the collection of all my error checks:
public void errorCheck() {
this.checkRow();
this.checkColumn();
this.checkBox();
}
Here i load it into my main. The code is a lot more elaborate, but these should be the sections involving the issue.
public static void main(String[] args) throws Exception {
Sudoku s = new Sudoku("C:\\Users\\caspe\\Downloads\\Sudoku001.sdk");
s.printBoard();
s.errorCheck();
s.getNum();
while(getNum() > 0) {
System.out.println("Next move, please (row , column , value )");
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt() ;
int value = scanner.nextInt();
if (s.moves(row, column, value)); {
s.errorCheck();
}
s.printBoard();
}
}
The issue
You're using charAt and trying to compare the result of that to a number:
list.get(j).charAt(i) == a
However doing so you're comparing the ascii value of the character to the number.
Example:
String a = "3";
System.out.println((int) a.charAt(0)); // This prints 51
The solution
If you wanted to compare number values you'd have to do something like this:
String a = "3";
System.out.println(Character.getNumericValue(a.charAt(0))); // This prints 3
Character.getNumericValue(a.charAt(0)) returns the number value of the character.
Implementation
Implementing that into your code would look like this:
Character.getNumericValue(list.get(j).charAt(i)) == a
This line:
if(list.get(j).charAt(i) == a)
is always false because you compare a char with an int.
Replace it with
if((list.get(j).charAt(i)-'0') == a)
list.get(j).charAt(i)-'0' gives you the numeric representation of the char
the problem is:
'if(list.get(j).charAt(i) == a)'
its comparing with the "a" value on the ascii table

How do I make this output happen in java?

I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure.
output:
Jamaica
amaica
maica
aica
ica
ca
a
What can I do, in order to achieve this output?
First: You need to loop for generating n line which is the length of array.
Second: You need to print the spaces with is same value as row - 1 number of times.
Second: You need to print character start from row - 1 number to the length of the string.
And the final solution will be:
public class MyClass {
public static void printStr(String str) {
int i,j;
for (i = 0; i < str.length();i++) {
for(j = 0; j < i; j++) {
System.out.print(" ");
}
for(j = i; j < str.length();j++) {
System.out.print(str.charAt(j));
}
System.out.println("");
}
}
public static void main(String args[]) {
MyClass.printStr("Jamaica");
}
}
I would use two regular expressions, the first to terminate the loop when the String is filled with white space. The second to replace the first non-white space character with a white space in the loop body (after printing the current String value). And, if it's possible the String might be empty you should guard against that. Like,
String s = "Jamaica";
if (!s.isEmpty()) {
while (!s.matches("\\s+")) {
System.out.println(s);
s = s.replaceFirst("\\S", " ");
}
}
Outputs (as requested)
Jamaica
amaica
maica
aica
ica
ca
a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next(); //input through scanner class
int len = s.length();
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
System.out.print(" ");
}
for(int j=i;j<len;j++){
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
Hopefully that helps
Try following code:
StringBuilder country = new StringBuilder("Jamaica");
for(int i=0; i< country.length();i++){
if(i > 0)
{
for(int j=0;j<i;j++){
country.setCharAt(j,' ');
}
}
System.out.println(country);
}

interviewstreet.com - String similarity

I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources