i am currently learning java, bellow are my current code
import java.util.*;
public class numbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How big is the array: ");
int size = input.nextInt();
int[] numb = new int[size];
for (int i=0;i<size;i++)
{
numb[i] = i;
}
//change value of last 3 index of array to 0
for (int i =0; i<size;i++)
{
System.out.println(numb[i]);
}
}
}
Here are how the output if i ran it currently
How big is the array: 7
0
1
2
3
4
5
6
how could i change the value of the last 3 index to 0? bellow are my expected output
How big is the array: 7
0
1
2
3
0
0
0
thanks in advance!
You can loop through the last 3 index and set it to 0.
for (int i = 1; i <= 3; i++) {
num[num.length - i] = 0;
}
You mean?
//change value of last 3 index of array to 0
for (int i = size-1; i >= size-3;i--)
{
numb[i] = 0;
}
//OR
for (int i = size-2; i<size;i++)
{
numb[i] = 0;
}
for (int i = 0; i<size;i++)
{
System.out.println(numb[i]);
}
This should do the trick:
//change value of last 3 index of array to 0
if (size <= 3) {
for (int i =0; i<size;i++)
{
numb[i] = 0;
}
} else {
for (int i=size-3; i<size; i++) {
numb[i] = 0;
}
}
Just subtract 3 from the size, it will work perfectly
for (int i=0;i<size-3;i++)
{
numb[i] = i;
}
Related
This is my program output:
Enter the size of 2D array:
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
and I need this instead:
1 12 5 16
2 11 6 15
3 10 7 14
4 9 8 13
I want the 2d array to be of size NxN where n is the integer inputted by the user. I want the first consecutive values to be stored in the even indexed columns from top to bottom and the next consecutive values to be stored in the odd indexed columns from bottom to top.
import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}
}
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println("\n");
}
}
public static int[][] transpose (int[][] array) {
if (array == null || array.length == 0)//empty or unset array, nothing do to here
return array;
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
return array_new;
}
}
As Sean pointed out in the comments, your transpose() function returns a new array but you are not capturing that and using it. The original array remains unchanged, which is what you are displaying at the end.
Change:
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
To:
int[][] newArr = transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : newArr) {
Try this out. It should do what you have described in the question.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int j = 0; j < n; j += 2) {
for(int i = 0; i < n; i++) {
arr[i][j]=inc++;
}
}
for(int j = 1; j < n; j += 2) {
for(int i = n - 1; i >= 0; i--) {
arr[i][j]=inc++;
}
}
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println();
}
}
I need to take 2 inputs from user size of array and then elements of that same array.
I need to print every third element of array.
Example Array: 1,2,3,4,5,6,7,8,9
Desired output: 3,6,9
Getting: 9,6,3
class Demo {
public static void main(String[] args) {
int x;
int[] y;
Scanner tastatura = new Scanner(System.in);
System.out.println("Enter size of array:");
x = tastatura.nextInt();
y = new int[x];
System.out.println("Enter the elements of array:");
for (int i = 0; i < x; i++) {
y[i] = tastatura.nextInt();
}
System.out.println("\n Every third element of array is : ");
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
tastatura.close();
}
You were close! You just have the iteration order reversed!
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
Should be:
for (int i = 2; i < y.length; i += 3) {
System.out.println(y[i]);
}
Take note that this can throw an ArrayIndexOutOfBoundsException if your array does not contain at least 3 elements, so you should handle that somewhere.
use the modulus operator to find each 3rd item.
example
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
for (int i =0 ; i < y.length - 1; i = i + 3) {
System.out.println(y[i]);
}
The way you are printing is in reverse order .. Correct that
You are on the right track I would strongly recommend using a modulus:
for (int i = 0; i < y.length; i++) {
if(i%3==0){
System.out.println(y[i]);
}//if statement
}//for loop
I can not find why the code has the last incorrect value for test 3 and 5. I can not change the array to array list. The methods are the only thing that I can change.
package Semester;
import java.util.ArrayList;
public class MemberArrayList {
private ArrayList<Integer> friendsScore = new ArrayList<Integer>();
private ArrayList<String> friendsID = new ArrayList<String>();
// Add a friend with ID with the score into friends.
public void addFriend(String friendID, int score) {
// TODO
friendsScore.add(score);
friendsID.add(friendID);
}
// Removes a friend with friendID, but you cannot use indexOf. Only methods you can use: size, equals, get, remove
public void removeFriend(String friendID) {
// TODO
for (int i = 0; i < friendsID.size(); i++)
{
if ( friendID.equals(friendsID.get(i)))
{
friendsScore.remove(i);
friendsID.remove(i);
}
}
}
// Get the scores of first 10 friends added
public int [] getScores10() {
// TODO
int size = 10;
int[] score = new int[size];
for (int i = 0; i < 10; i++)
{
score[i] = friendsScore.get(i);
}
return score;
}
public int [] getScoresLast10() {
// TODO
int[] score = new int[10];
int j = 0;
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
{
score[j] = friendsScore.get(i);
j++;
}
return score;
}
// Get the scores of the friends in the array, but you cannot use indexOf function. You can only use size, get, equals, intValue
public int [] getScores(String [] friendIDs) {
// TODO
int value = friendIDs.length;
int[] score = new int[value];
for (int i = 0; i < value; i++)
{
String person = friendIDs[i];
for (int j = 0; j < friendsID.size(); j++)
{
if (person.equals(friendsID.get(j)))
{
score[i] = friendsScore.get(j);
}
}
}
return score;
}
public static void main(String[] args) {
MemberArrayList member = new MemberArrayList();
member.addFriend("Paul", 3);
member.addFriend("Peter", 1);
member.addFriend("Mary", 2);
member.addFriend("John", 4);
member.addFriend("Karen", 7);
member.addFriend("Kevin", 3);
member.addFriend("Walter", 1);
member.removeFriend("Mary");
member.removeFriend("Walter");
member.addFriend("Steven", 21);
member.addFriend("Kelly", 9);
member.addFriend("Kaitlin", -5);
member.addFriend("Bea", 77);
member.addFriend("Max", 32);
System.out.println("Test 1");
String [] friendIDs = {"Paul","Kevin","Steven","Max"};
int [] scores = member.getScores(friendIDs);
for (int i = 0; i < scores.length; i++)
System.out.println(friendIDs[i]+" "+scores[i]);
System.out.println("Test 2");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 3");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
member.removeFriend("Bea");
member.addFriend("Eric", -1);
member.addFriend("Abby", -2);
member.addFriend("Jacob", 3);
member.addFriend("Blake", 8);
System.out.println("Test 4");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 5");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
}
}
The output should be
Test 1
Paul 3
Kevin 3
Steven 21
Max 32
Test 2
3
1
4
7
3
21
9
-5
77
32
Test 3
32
77
-5
9
21
3
7
4
1
3
Test 4
3
1
4
7
3
21
9
-5
32
-1
Test 5
8
3
-2
-1
32
-5
9
21
3
7
Your loop for counting down is missing one value to copy:
Wrong:
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
This runs for 9 times.
Right:
for (int i = friendsScore.size()-1; i >= (friendsScore.size()-10); i--)
This runs 10 times and copies all 10 values to the array. Note the >= instead of >.
With the first loop the last value of your array will never be set and so defaults to 0 or whatever your compiler might set (I think it is always 0 in java but I'm not sure).
I'm unsure if the problem in my program is simply in where I declared the arrays, or if I'm stuffing one of them with more than they can take.
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
public class EliminateDuplicates {
public static void main(String[] args) {
int[] numberList = new int[10];
System.out.println("Please enter ten integers.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < numberList.length; i++) {
numberList[i] = input.nextInt();
}
int[] newNumberList = new int[10];
newNumberList = eliminateDuplicates(numberList);
System.out.println("The discrete numbers are: ");
for (int i = 0; i < newNumberList.length; i++) {
System.out.println(newNumberList[i] + ' ');
}
}
public static int[] eliminateDuplicates(int[] numberList) {
int[] noDuplicateList = new int[numberList.length];
int size = 0;
java.util.Arrays.sort(numberList);
for (int i = 0; i < numberList.length; i++) {
if (numberList[i] != numberList[i+1]) {
noDuplicateList[i] = numberList[i];
size++;
}
}
return noDuplicateList;
}
}
This is the output + the error message I get:
Please enter ten integers.
9
8
7
3
3
4
1
2
8
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at EliminateDuplicates.eliminateDuplicates(EliminateDuplicates.java:51)
at EliminateDuplicates.main(EliminateDuplicates.java:28)
Your problem is here :
for (int i = 0; i < numberList.length - 1; i++) {
if (numberList[i] != numberList[i+1]) {
When i reaches numberList.length-1, i+1 is out of the array bounds.
You should change the range of the loop. You shold also use the size index when assigning to the noDuplicateList list, otherwise you will have gaps in that list.
for (int i = 0; i < numberList.length - 1; i++) {
if (numberList[i] != numberList[i+1]) {
noDuplicateList[size] = numberList[i];
size++;
}
}
You would still have a minor problem. Since your eliminateDuplicates methods returns an array of the same size as the input, if there were duplicates, the output array would have unused indices in its end (that will contain zeroes). If you wish to avoid that, you can add all the items of the input array to a HashSet, find the size() of that set, and create an array of that size for the output. Using a Set will also simplify your code, since the Set would eliminate the duplicates for you, and you don't have to sort the input array.
public static int[] eliminateDuplicates(int[] numberList) {
Set<Integer> noDups = new HashSet<Integer>();
for (int num : numberList)
noDups.add(num);
int[] noDuplicateList = new int[noDups.size()];
Iterator<Integer> iter = noDups.iterator();
for (int i=0; i<noDuplicateList.length && iter.hasNext();i++)
noDuplicateList[i]=iter.next();
return noDuplicateList;
}
Your problem is here, eliminateDuplicates:
if (numberList[i] != numberList[i+1]) {// i+1, for the last elements raise the exception
if (numberList[i] != numberList[i+1])
when i=9 this would look for index 10 which is out of bound.
the problem is this line:
if (numberList[i] != numberList[i+1]) {
If i is equals numberList.length the second condition is out of bounds.
So you have to change:
for (int i = 0; i < numberList.length; i++) {
TO:
for (int i = 0; i < numberList.length-1; i++) {
Ok so this is my code. I'm supposed to gather 10 numbers of input and then sort them in descending order by the number of which they appear.
Ex. {0,0,1,2,2,2]
My output would be "Mode=2 and then have 2 appears 3 times, 0 appears two times, 1 appears once."
My code can gather the 10 integers and find the mode but I'm having issues trying to sort the numbers in that way. This is what I have so far and I'm stuck.
import java.util.*;
class question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arrTwo = new int[10];
int x=0;
for (int i = 0; i < 10; i++)
{
System.out.println("Enter number: " + (i + 1));
arrTwo[i] = scan.nextInt();
}
mode(arrTwo);
int temp;
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x )
{
if (bs[x]>bs[x+1])
{
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
for(int i = 0; i <= bs.length-1; i++)
{
for(int index=0; index <= 99 ; index++)
{
if (i == i)
{
bs[i] +=1;
}
}
System.out.println("The number " + i + " is generated " +arrTwo[i] + " times");
}
}
public static void mode(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println("The mode is: "+maxIndex);
}
My output isn't listing my numbers, just 0-9 and the generated times is just going from 1-9 with no basis or order.
this code:
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x ){
if (bs[x]>bs[x+1]) {
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
does nothing. On initialization bs is filled with zeroes bs[x-1] is never greater than bs[x] because all values are the same.
also
if (i == i){
is always true