I've written that piece of code in which I scanned an integer suppose 121 and for dividing it into 3 part I make it a String and tried to convert it again by splitting.But I am not getting the way? Is there any simple way to make it so?
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt() ;
int sum = 0;
for(int i = 1 ; i<=n; i++){
String s = Integer.toString(i);
int[] c = Integer.parseInt(s.split("")); //Here's the problem
int sm = 0 ;
for(int x :c){
sm +=x ;
}
System.out.print(sm+" ");
}
}
input = 12
expected output: 1 2 3 4 5 6 7 8 9 1 2 3
output : Main.java:14: error: incompatible types: String[] cannot be
converted to String
int[] c = Integer.parseInt(s.split(""));
Your expected output would not even seem to need any integer to string conversion:
int n = scan.nextInt();
for (int i=0; i < n; i++) {
if (i > 0) System.out.print(" ");
System.out.print(1 + i % 9);
}
For an input of n = 12, this prints:
1 2 3 4 5 6 7 8 9 1 2 3
You can't pass the whole array to parseInt(). You need to parse each element individually:
int[] c = Arrays.stream(s.split(""))
.mapToInt(Integer::parseInt)
.toArray();
Or the old-fashioned way:
String[] chars = s.split("");
int[] c = new int[chars.length];
for (int i = 0; i < c.length; i++) {
c[i] = Integer.parseInt(chars[i]);
}
You could map each character from the String[] (from the split) to an int, and then convert that to an int[]. Like,
int[] c = Arrays.stream(s.split("")).mapToInt(Integer::parseInt).toArray();
with no other changes, that produces (as requested)
1 2 3 4 5 6 7 8 9 1 2 3
With input of "12".
You can also do it like this using an IntStream.
int n = 12;
int[] values = IntStream.range(0, n).map(i -> i % 9 + 1).toArray();
System.out.println(Arrays.toString(values));
Produces
[1 2 3 4 5 6 7 8 9 1 2 3]
for n = 12
Related
given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers.
Examples:
Input: arr[] = 1 9 5 3 2 6 7 11
Output: 2 6 5 3 1 9 7 11
Input: arr[] = 1 3 2 4 7 6 9 10
Output: 2 4 6 10 7 1 9 3
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[]= { 1, 3, 2, 4, 7, 6, 9, 10 };
int n=a.length;
int ind=0;
for(int i=0;i<n;i++){
if(a[i]%2==0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
if(a[i]%2!=0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
System.out.println(a[i] + " ");
}
System.out.println("");
}
}
I am getting output like this
2
4
6
10
7
9
9
10
0th index and 1st index not calculate.
what mistake I made, please guide me.
You're program is almost correct, but needs little modification, below is the implementation and explanation
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[] = { 1, 9, 5, 3, 2, 6, 7, 11 };
int n = a.length;
int evenIndex = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
int temp = a[i];
a[i] = a[evenIndex];
a[evenIndex] = temp;
evenIndex++;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
} }
What are we doing here:
We maintain a evenIndex pointer at 0 index
Whenever we find any Even value we swap it with evenIndex i.e.., arr[evenIndex] = arr[i] and place arr[i] = arr[evenIndex]
This code works does not modify any values if you pass an array with only Even Numbers or Odd Numbers
Time Complexity : O(n)
Space Complexity : O(1)
This can also be accomplished by sorting the array based on the value of each element modulo 2.
int[] a= { 1, 3, 2, 4, 7, 6, 9, 10 };
int[] res = Arrays.stream(a).boxed().sorted(Comparator.comparingInt(x -> x & 1))
.mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(res));
I have been working on this program and randomly shuffles the contents of an array of integers.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Do you wish to shuffle these numbers? y
Array contents: 5 12 7 10 6 9 15 1 13 3 4 11 14 2 8
Do you wish to shuffle these numbers? y
Array contents: 2 9 15 4 12 11 3 7 10 8 1 6 13 5 14
Do you wish to shuffle these numbers? n
This is what im getting:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Do you wish to shuffle these numbers? y
Exception in thread "main" java.lang.NumberFormatException: For input string: "y"
and says build failed
This is the main code:
public class Evao1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shuffler myShuffler = new Shuffler(size);
Scanner input = new Scanner(System.in);
for(;;) {
myShuffler.display();
System.out.println();
System.out.print("Do you wish to shuffle these numbers? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
}
}
}
Here is the additional class:
public class Shuffler {
private int[] data;
public Shuffler(int size){
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = i + 1;
}
}
public void shuffle(){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void display()
{
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
}
}
The problem is with the last two lines of your for loop in the Evao1 class.
First, I think you meant to write if (value.equals("n")) break;
Second, instead of int value1 = Integer.parseInt(value);
Just do myShuffler.shuffle();
Also, in the for loop of display() you aren't actually displaying anything from the data array.
Change values += (i + 1); to values += data[i];
I have been working on this program and will display the array contents to the user and ask how many positions he would like to shift off the right side of the array, and replace onto the left side.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Shift how many positions? 5
Array contents: 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10
Shift how many positions? 2
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? 0
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? -8
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 15
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 17
Array contents: 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Shift how many positions? q
And im getting this:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Shift how many positions?5
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Here is the main class:
public class Shift1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
test.display();
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Shift how many positions?");{
int value1 = input.nextInt();
test.shift(value1);
test.display();
}
}
}
And here is additional class:
public class Shifter
{
public int [] data=new int[15];
public Shifter()
{
int size=0;
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void shift(int pos){
for(int x=0; x<pos; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
} }
Introduce a loop in main() method.
Firstly read as string in order to recognize q.
Implement Shifter.shift() properly.
Add a space after the prompt.
Initialize the array properly.
Implement Shifter.display() properly.
Corrected codes:
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
Scanner input = new Scanner(System.in);
for(;;) {
test.display();
System.out.println();
System.out.print("Shift how many positions? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
test.shift(value1);
}
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
data[i] = i + 1;
}
}
public void shift(int pos){
int max = pos % data.length;
if (max < 0) max += data.length;
for (int x=0; x<max; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt-1];
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
values += " ";
if (data[i] < 10) values += " ";
values += data[i];
}
System.out.printf("Array Contents: %s \n", values);
}
Though there are more points to be improved, this works as you said.
for(int x=0; x<pos; x++) {
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--) {
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
In your shift method you should be utilizing your x for loop variable. cnt and temp are always the same no matter what. So your not really doing anything in this loop.
If your allowed to use something other than an Array, maybe take a look at using a List. It has a unique method such as
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int,%20E)
which will allow you to add a number at the 0 index and it will auto shift the existing values right. So pop a value off the end and move it to the front size amount of times.
I have an ArrayList:
ArrayList<Integer> list = new ArrayList<>();
And an Array of Integers:
int[] x = {5, 10, 15, 20, 25};
I want to execute each Array of Integers in a certain position of the ArrayList. I’ve tried the following code but it's not working as expected!
public static void main(String[] args) {
// TODO code application logic here
for(int i = 1; i <= 30; i++) {
list.add(i);
}
for(int i = 0; i < list.size(); i++) {
System.out.print(i);
System.out.print(" , ");
System.out.print(number(i));
}
}
private static long number(int pos) {
int y = 0;
return (long) pos / list.get(x[y]);
}
Current Output:
0 , 0
1 , 0
2 , 0
3 , 0
4 , 0
5 , 0
6 , 1
7 , 1
8 , 1
9 , 1
10 , 1
11 , 1
12 , 2
.
.
.
Expected Output (something like):
0 , 0
1 , 0
2 , 0
3 , 0
4 , 0
5 , 5
6 , 5
7 , 5
8 , 5
9 , 5
10 , 10
11 , 10
12 , 10
.
.
.
I tried different methods but couldn't manage to solve it, any help is very much appreciated.
I will answer like you want to follow the pattern in your expected answer, first of all, when you say list.get(x[y]) it gives you list.get(5) which is 6 as you started to count from 1 not 0 when filling the list, So you are preferred to do one of two options:
1- make your count from 0:
for(int i = 0; i < list.size(); i++) {
.
.
}
2- make your get line with x[y]-1:
list.get(x[y] - 1);
And in both cases when you want to get the result, you must multiply it with the value of the list index which is x[y]:
private static long number(int pos) {
int y = 0;
return Math.round(pos / list.get(x[y]) * x[y]);
}
I think it's because y variable inside number method is always 0. Because of that number method always returns pos / list.get(5). That's why 2nd number increases when number is divisible by 6. From what I noticed your expected output is number divided by 1 rounded down to nearest 5.
What I suggest you to do is to maintain a counter variable to check if the number in the array has reached or not.
int []arr = {2, 5, 10, 15, 20, 30};
int size = arr[arr.length - 1];
ArrayList<Integer> list = new ArrayList();
int k = 0;
for(int i = 0; i < size; ++i)
{
if(i == arr[k])
k ++;
if(k == 0)
list.add(0);
else
list.add(arr[k - 1]);
}
for(int i = 0; i < size; ++i)
System.out.println(i + ", " + list.get(i));
Output:
0, 0
1, 0
2, 2
3, 2
4, 2
5, 5
6, 5
...
private static long number(int pos) {
return list.get(pos);
}
I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Here is my code:
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
System.out.print(Math.min(k, i * 2 - k) + " ");
}
System.out.println();
}
}
}
It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= (numrow - i); j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
int temp = Math.min(k, i * 2 - k);
if (temp > 9) {
System.out.print(temp + " ");
} else {
System.out.print(temp + " ");
}
}
System.out.println();
}
}
}
In this example I counted the digits, and for every digit I add an extra space.
The output of the value is formatted with leading zeros (digit-count).
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
final int numrow = 100;// sc.nextInt();
final int digits = (int) Math.log10(numrow) + 1;
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
for (int l = 0; l < digits; l++) {
System.out.print(" ");
}
}
for (int k = 1; k < i * 2; k++) {
final int value = Math.min(k, i * 2 - k);
System.out.print(String.format("%0" + digits + "d ", value));
}
System.out.println();
}
}
You can use String.format method:
"%2d" - format as a two-digit number.
"%02d" - format as a two-digit number with leading zeros.
Example:
// int n = 5;
int n = 12;
// number of digits
int digits = String.valueOf(n).length();
// format string
String format = "%" + digits + "d";
// output
System.out.println("n=" + n + ", format=" + format);
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.rangeClosed(-n, i)
.map(Math::abs)
.map(j -> j = i - j)
.filter(j -> j != 0)
.mapToObj(j -> j > 0 ?
String.format(format, j) : " " .repeat(digits))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
Output:
n=5, format=%1d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
n=12, format=%2d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1
See also: Print the sum of the row and column in a 2d array after each row