I have to take a user input of integers from a range, convert that to binary, and fill a 3x3 array with the binary. The only problem is, my code is giving me an output of only dependent on the first 3 numbers of that binary (i.e 010001101 = 010 across all rows).
import java.util.Scanner;
public class HW11P02 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
listArray(binary);
};
public static String[][] listArray(String binary) {
String[][] array = new String[3][3];
char ch = ' ';
String value = "";
for (int i = 0; i < 3; i++) {
for (int n = 0; n < 3; n++) {
ch = binary.charAt(n);
value = Character.toString(ch);
array[i][n] = value;
System.out.print(array[i][n] + " ");
}
System.out.println();
}
return array;
}
};
I think this will provide the the output you may really want.
import java.util.Scanner;
public class HW11P02
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
int result[][]=new int[3][3];
int position=0;
for (int i = 0; i < result.length; i++)
{
for (int j = 0; j < result.length; j++)
{
result[i][j]=binary.charAt(position++)-'0';
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
Related
I need to fill 2D array using input without spaces, so for this I'm trying to use 'String' firstly.
import java.util.Scanner;
import java.util.Arrays;
public class TikTakToe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0, l = 0; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
for (char[] chars : TikTakToe) {
System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]",
"").replace(", ", " "));
}
}
}
Input: XOXOXOXOX
Output:
X O X
X O X
X O X
The problem in this solving that variable 'l' resets after outer 'for' loop goes to the next stage. How can I fix it?
You're problem is that you defined the variable l in the nested for loop. Consequently, when that loop returns, l is deleted.
What you would need to do is define l before the first loop, that way its scope is the whole method.
...
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // <-- **I moved the declaration here**
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0 /*removed the declaration from here*/; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
...
You should initialize int l = 0 outside the loop. As it will be re-initialized when inner loop will run.
So your final code would look like :-
import java.util.Scanner;
import java.util.Arrays;
public class TikTakToe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // initialize here
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
for (char[] chars : TikTakToe) {
System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]",
"").replace(", ", " "));
}
}
public static void find( int[] numbers) {
int[] range = new int[5];
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[i]=range[i]+numbers[i];
}
}
}
I want to write a method that find the numbers between 10 and 20 in a array and assign them to another array. this is expected and this is what I got.
{ 0 0 0 } are between 10 - 20 how can I fix this ?
public static void read( int[] numbers) {
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
}
This is the read() method that reads numbers from user and assign to an array.
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
And this is the print(x,y) method that prints the numbers and range arrays.
My main method is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
read( numbers );
int[] range = new int[5];
find( numbers );
print(numbers, range);
The numbers array must include 3 numbers between 10-20.
Solution
Change the return type of your function to int[]
precalculate the size of your ranges array with counter
store the values which are in your range in the range array
return the range array
Note dont use the i running variable also for your range array, if you do so when not every value is in your range the result array will have gaps meaning values with the value of zero.
In the read function you should return the readed-in values to use it then in your find function
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for(int i=0; i < size; i++)
{
System.out.print("Number["+(i+1)+"] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
import java.util.*;
public class MyClass {
public static void main(String args[]) {
int[] values = MyClass.read(10);
int[] result = MyClass.find(values);
// result is now the return value of the find method
// you can parse it now to another method of your choice
System.out.println(Arrays.toString(result));
}
public static int[] find(int[] numbers) {
int counter = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
counter++;
}
}
int[] range = new int[counter];
int counter2 = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
range[counter2] = numbers[i];
counter2++;
}
}
return range;
}
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Number[" + (i+1) + "] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
}
1. You need to return the 'range' array in the 'find' function because otherwise, it isn't accessible.
2. You need another variable say 'j' to point to the indices of the 'range' array.
The same variable can't be used for both the 'numbers' array and the 'range' array.
3. It will be better to pass the size of the 'numbers' array through the 'read' function and then read the array using the 'read' function.
Functions:
find() function:
public static int[] find( int[] numbers) {
int[] range = new int[5];
int j = 0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[j]=range[j]+numbers[i];
j++;
}
}
return range;
}
read() function:
public static int[] read( int n) {
int[] numbers = new int[n];
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
return numbers;
}
print() function[Remains same]:
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
Main function accordingly:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] numbers = read(n);
int[] range = find(numbers);
change(numbers);
print(numbers, range);
}
I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}
package examples;
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
The below 4 sections identifies user input for the rows and columns of two matrices.
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
This sets the objects matrix1 and matrix2 as belonging to the class Matrix
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c];
This originally served to allow the user to input values of a matrix one by one. For now I just set all values of the matrix to a certain value for simplicity.
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
//Scanner userelement = new Scanner(System.in);
//System.out.println("Enter number:");
//int element = userelement.nextInt();
values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < rows; k++) {
for(l = 0; l < columns; l++) {
System.out.println(values[k][l] + " ");
}
System.out.println("\n");
}
}
}
The code is above. In the final method in the class Matrix (the method is ShowMatrix), I am trying to print out the matrix. However, I am using the general values matrix here and it says:
Exception in thread "main" java.lang.NullPointerException
at examples.Matrix.ShowMatrix(MatrixMultiplication.java:75)
at examples.MatrixMultiplication.main(MatrixMultiplication.java:29)
Can anyone diagnose the issue? Much thanks as I'm still very new to Java.
You've not instantiate the field [][]values (There is a local declaration of int[][] values).
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c]; <-- Remove this
values = new int[r][c];
....
}
Just remove the package line if you are using the terminal or command prompt.
package examples;
Working Code:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
//int[][] values = new int[r][c];
this.values = new int[r][c];
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
this.values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < this.rows; k++) {
for(l = 0; l < this.columns; l++) {
System.out.print(this.values[k][l] + " ");
}
System.out.println("\n");
}
}
}
One more suggestion is that there is no need of creating new instance/object for Scanner class for each row and column.
Scanner userInput = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns1 = userInput.nextInt();
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns2 = userInput.nextInt();
I am new at java programming and am working on an exercise where the user is to input ints into an array and then stop the user input by entering a negative int value. All works well except the array prints 0 beyond the user input. So if a user enters 5 values and then one negative value only the five values should print not the user input values and 95 0s.
Any assistance would be greatly appreciated.
Here is my code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array [i] < 0)
{
break;
}
}
for (int i =0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
When you declare an int in Java, it will default to 0 if you do not specify a value for it. When you declare your array,
int array[] = new int [100];
You are essentially making an array of 100 0's. You can see a small example of this by running the following code:
public static void main(String[] args) throws Exception {
int array[] = new int [1];
System.out.println("The value of i is: " + array[0]);
}
What you could do, is store the negative value into your array, and then stop printing if you reach that value.
for (int i =0; i<array.length; i++){
if(array[i]<0){
break;
}
System.out.println(array[i]);
}
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
int totalValuesEntered = 0;
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array[i] < 0)
{
totalValuesEntered = i;
break;
}
}
System.out.println("Your entries are:");
for (int i =0; i<totalValuesEntered; i++)
{
System.out.println(array[i]);
}
}
You are looping 100 times no matter what on the last loop, and you are saving the userinput no matter what they enter.
In order to achieve what you want. Declare a new integer enteredValues to count how many values the user entered before exiting.
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System. in );
int array[] = new int[100];
System.out.println("Enter values up to 100 values, " +
"enter a negative number to quit");
int enteredValues = 0;
for (int i = 0; i < array.length; i++) {
int userInput = scan.nextInt(); //save nextInt to a variable
if (userInput >= 0) {
array[i] = userInput;
enteredValues++;
} else{
break;
}
}
for (int i = 0; i < enteredValues; i++) {
System.out.println(array[i]);
}
}