Tables trouble. I need help to make them - java

I want to make a list going to n numbers depending on user input. I then want to put a second number in each place and print the entire table. As for testing I have tried with a length 4 and numbers 1,2,3,4 but I get a error: ArrayIndexOutOfBounds. I wanted it to print 1,2,3,4.
Scanner keyboard = new Scanner (System.in);
System.out.println("Whats the length of the table?");
int lengde = keyboard.nextInt();
int[] minTabell = new int[lengde];
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
System.out.println(minTabell);
keyboard.close();

Indexes in Java arrays are 0-based, while your for-loop starts from 1. So,
for (int i =1; i <= lengde+ 1; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
should be
for (int i =0; i < lengde; i++) {
// ^ ^^^^^^^^
System.out.println((i+1) + (" give a number"));
// ^^^
minTabell[i] = keyboard.nextInt();
}
As for printing the content of the array, I suggest you use
for (int i : minTabell)
System.out.println(i);

In Java array indexing starts at 0. The first element is positioned at minTabel1[0]. Your for-loop runs from 1 to lengde + 1, which means that you will try to fill a position outside of the array.

The first element of an array has the index 0. The last valid index of your array is lengde-1.
Try this:
for (int i=0; i < lengde; i++) {
System.out.println((i) + (" give a number"));
minTabell[i] = keyboard.nextInt();
}
To print the array, i suggest the following:
System.out.println(Arrays.toString(minTabell));

Related

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Collections.rotate not working

I can't get Collections.rotate to work. When I enter qwerty into userInputCharacters and run this code, it just ends up outputting qwerty again. Any recommendations?
Collections.rotate(Arrays.asList(userInputChararacter), 2);
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
UPDATE: Here is my full program.
import java.util.*;
public class WrapAround
{
public static void main(String[] args) throws java.io.IOException
{
//Create a scanner to read the users input.
Scanner userInput = new Scanner(System.in);
//Get the amount of characters the user wants to input.
System.out.println("How many character do you want to enter?");
int characterAmount = userInput.nextInt();
//Get and put the user's characters into an array.
System.out.println("Please enter your " + characterAmount + " characters.");
String userInputString;
userInputString = userInput.next();
char[] userInputChararacter = new char[characterAmount];
for(int index = 0; index <= characterAmount - 1; index++)
userInputChararacter[index] = userInputString.charAt(index);
//Get what number character the user wants to start with.
System.out.println("Which character do you want to start with?");
int startingCharacterIndex;
startingCharacterIndex = userInput.nextInt();
startingCharacterIndex--;
//Give the user their characters in order.
System.out.println("Here are all your characters, beginning with number " + (startingCharacterIndex + 1) + ".");
userInputChararacter = Collections.rotate(Arrays.asList(userInputChararacter), (startingCharacterIndex - 1));
for(int index = 0; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
/*
for(int index = startingCharacterIndex; index <= characterAmount - 1; index++)
System.out.print(userInputChararacter[index]);
for(int index = 0; index <= startingCharacterIndex - 1; index++)
System.out.print(userInputChararacter[index]);
*/
System.out.println();
}
}
The reason it doesn't work is that Arrays.asList(new char[]{'q','u','e'}) will create a list of size 1, not 3. It's different from Arrays.asList('q','u','e') where elements will be correctly autoboxed to Character and list of size 3. Consequently your rotation is not going to change anything.
You should create your own List<Character> instance by adding elements or creating a wrapper class for the underlying array.
Or, perhaps easier to eliminate char altogether and represent even single chars as Strings.

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

What do I need to do to my current code to make the program run a multiplication table (using a two dimensional array)?

I'm trying to make a Java program that uses the input value from a user to calculate and list the products of two numbers up to the entered number. Like if a user enters 2, the program should calculate the products between the two numbers (1 *1, 1*2, 2*1, 2*2) stores the products in a two-dimensional array, and list the products. I'm not sure that I totally understand arrays and so I feel as though my code is problem not right in many instances, can someone please tell me what I should do to my current code to make it work properly. Thanks in advance! :)
import java.util.Scanner;
public class ProductTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputString;
char letter = 'y';
// Prompt the user to enter an integer
while(letter != 'q') {
System.out.print("Enter a positive integer: ");
int integer = input.nextInt();
// Create an two-dimensional array to store products
int[][] m = new int[integer][3];
for (int j = 1; j <= m.length; j++) {
m[j][0] = input.nextInt();
m[j][1] = input.nextInt();
m[j][2] = input.nextInt();
}
// Display the number title
System.out.print(" ");
for (int j = 1; j <= m.length; j++)
System.out.print(" " + j);
System.out.println("\n--- ");
// Display table body
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Prompt the user to either continue or quit
System.out.print("Enter q to quit or any other key to continue: ");
String character = input.nextLine();
inputString = input.nextLine();
letter = inputString.charAt(0);
}
}
}
You can achieve your multiplication table by iterating over 2 counter variables as you already did in your output
// Display table body
// loops running out of bounds (until m.length + 1 instead of m.length-1)
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) { // missed to increment j here
System.out.printf("%4d", i * j);
}
System.out.println();
}
Arrays should be based on 0, that means an array with 3 fields has the indexes 0, 1, 2. So the last index is length-1. Your condition <=m.length+1 runs out of bounds. index<length will work since 2 is less than 3, but not 3 less than 3.
You have also a typo: In the inner loop you are doing an increment of i instead of j, so the loop will run infinite.
Try to create an outer and inner loop as you did, but with start index 0 and end condition index<inputValue. Calculate multiTable[index1][index2] = (1+index1)*(1+index2).
Then do a similar loop and print the array fields. You don't need to use an array, you could output directly as you did. But you wanted to practice handling arrays.
Since you want to learn and understand, I don't like just to write the code. imagine an array with 3 fields having the indexes 0, 1, 2:
index 0 | 1 | 2
value 1 | 2 | 3
Now you would check the length at first, that's 3. You start with 0 and count while the counter does not reach the length since the zero based index is 1 below our natural order (0,1,2 vs. 1,2,3). That is the case as long the index is below the length, meaning index<length.
Try this logic (pseudo code). To simplify the problem we include the 0 in our product table. So we get 0*0, 0*1, 0*2... Doing so, we do not have to ignore index 0 or to calculate between index 0 should represent value 1.
maxNumber = userInput()
outer loop idx1 from 0 to maxNumber
inner loop idx2 from 0 to maxNumber
array[idx1][idx2] = (idx1) * (idx2)
end loop
end loop
Do the same to dump your generated array to screen.
First get it running. Afterwards you could try to alter the logic, so that it shows you only numbers from 1 to max.

Why is my code always allowing duplicate names?

I have a question about writing a code that can check if what the user inputs (a string) is a duplicate of a string that an array already stored:
First of all I want to point out I checked with the question on here about duplicates but they are either answered with importing packages other than Scanner or checking duplicates in an already int or string stored arrays. This is different:
int numberOfPigs = Integer.parseInt( keyboard.nextLine() );
Pigs pigArray = new pigs[numberOfPigs];
for (int i = 0; i < pigArray.length; i++){
System.out.println("Pig name: " + (i+1));
String name = keyboard.nextLine();
String [] tempArray = new String [numberOfPigs];
tempArray[i]=name;
for (int k = i+1; k < pigArray.length; k++){
while (tempArray[i].equals( tempArray[k])){
System.out.println("The ID is duplicate.");
tempArrays[i] = keyboard.nextLine();
}
System.out.println("Not a duplicate! Yay.");
}
...code not over. the for loop with int i still has to go through several inputs from user before looping back to the beginning and go through i++ with taking in the next pig name. The rest part of the code I have no problem with, it's just that whenever i run this code, the duplicates are still allowed in... Any tips are appreciated. Thank you.
You made 2 mistakes in your code.
You were redeclaring your tempArray in your initial for loop.
You were counting up in your k loop when you should have been counting down.
int numberOfPigs = Integer.parseInt(keyboard.nextLine());
Pigs pigArray = new pigs[numberOfPigs];
String[] tempArray = new String[numberOfPigs]; // I moved this here see
// comment below
for (int i = 0; i < pigArray.length; i++) {
System.out.println("Pig name: " + (i + 1));
String name = keyboard.nextLine();
// first problem was you were redeclaring your tempArray here
// thereby erasing previous elements over every iteration of i
tempArray[i] = name;
for (int k = i - 1; k >= 0; k--) { // you need to count backwards
//you only check what was already entered for duplicates
// you were doing the opposite
while (tempArray[i].equals(tempArray[k])) {
System.out.println("The ID is duplicate.");
tempArray[i] = keyboard.nextLine();
}
System.out.println(" Not a duplicate! Yay.");
}// k loop
}// i loop
int numberOfPigs = Integer.parseInt( keyboard.nextLine() );
Pigs pigArray = new pigs[numberOfPigs];
for (int i = 0; i < pigArray.length; i++){
System.out.println("Pig name: " + (i+1));
String name = keyboard.nextLine();
String [] tempArray = new String [numberOfPigs];
tempArray is now an array with numberOfPigs, where each element is null.
tempArray[i]=name;
Now the first element in tempArray is the user-input name, but all other elements are still null.
for (int k = i+1; k < pigArray.length; k++){
Why are you using pigArray.length, yet you are not using pigArray in the loop at all?
while (tempArray[i].equals( tempArray[k])){
In fact, you're comparing the first element in the array, which is not null (it's the user input), against all the other elements, which are null! Of course it won't think anything is a duplicate, because you're checking the it against a whole bunch of nothing.
Since the user-input name is never equal to null, that is being falsely interpreted as "not a duplicate", and allowed through.
System.out.println("The ID is duplicate.");
tempArrays[i] = keyboard.nextLine();
}
System.out.println("Not a duplicate! Yay.");
}

Categories