How to print the number of Array?
import java.util.Scanner;
public class ArrayTest {
public static void main(String[] args) {
String[] fruit = new String[5];
Scanner scan = new Scanner(System.in);
for(int i=0;i<fruit.length;i++)
{
System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
fruit[i] = scan.nextLine();
}
for(String a : fruit) {
System.out.println(a);
/*How do i add Like the number like this
1.Banana
2.Apple
instead of Banana
Apple
}
}
}
How do i add Like the number like this
1.Banana
2.Apple
instead of Banana
Apple
Though your question is not very clear, it seems you just want o print the array index with contents, in that case you can follow the below code:
for(int i=0;i<fruit.length;i++){
System.out.println((i+1)+"."+fruit[i]);
}
Or if you want the number to store the index in the array contents, then you can go with:
for(int i=0;i<fruit.length;i++)
{
System.out.print("Fruit number "+ Math.addExact(i, 1)+ ": ");
fruit[i] = (i+1)+"."+scan.nextLine();
}
Hope it helps.
Take a counter variable
int k=1;
then when you are printing the names just add it in front of the string inside System.out.print() and increment k after it
for(syntax)
{
System.out.println(k+"."+a);
k++;
}
or you can use
for(int k=0;k<fruit.length;k++){
System.out.println((k+1)+"."+fruit[k]);
}
and if you want to take input like that use
for(int k=0;k<fruit.length;k++)
{
System.out.print("Fruit number "+ Math.addExact(k, 1)+ ": ");
fruit[k] = (k+1)+"."+scan.nextLine();
}
i hope it will sollve ur problem
This code will show the index no with value.
int a[] = {2,9,8,5,7,6,4,3,1};
for(int i=0;i<a.length;i++)
{
System.out.println((i)+"."+a[i]+" ");
}
Output:0.2
1.9
2.8
3.5
4.7
5.6
6.4
7.3
8.1
You can either (1) use a for(int i=0...) loop like you did when scanning input, or (2) use a ListIterator. See How to get the current loop index when using Iterator? for an example.
Related
I keep trying different kinds of code and I always come back to this. but it never seems to work. The last if statement is making the i's underlined red but I can't even understand why. The homework was to make a program that takes user input and put it into an array and see if the user input is already sorted. Please Help!
import java.util.Scanner;
public class Sorting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the array size: ");
int a = input.nextInt();
System.out.println("Enter the numbers using spaces between each number: ");
int[] numbers = new int[a];
for (int i=0; i<numbers.length; i++)
{
numbers[i]=input.nextInt();
if(isSorted(numbers))
{
System.out.println("Sort is already sorted");
}
else
{
System.out.println("Sort is not sorted sorry");
}
}
}
public static boolean isSorted(int[] numbers)
{
for(int i = 0; i<numbers.length-1; i++);
{
if(numbers[i]>numbers[i+1])
{
return false;
}
}
return true;
}
}
Close the for loop before the if statement.
for(int i = 0; i<numbers.length-1; i++); //<===== remove the ';' here
I think you missed place the ; after the for loop and that cause your issue.
So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}
I am learning about arrays and I did quiet a few experiments, most of them went well, however now I'm stuck.
What I want to archive is, find if an specific value (String, int or whatever), exists inside an Array and if it does, use that value for something i.e the code below which I basically count how many times that value was present inside the array:
package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int arraySize = 0;
int wordCount = 0;
System.out.println("How many words are you gonna type?: ");
arraySize = sc.nextInt();
String[] words = new String[arraySize]; // Simple array, the size of which will be decided from the user-input
for(int count = 0; count < arraySize; count++)
{
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
}
//Basically this is the part I'm having troubles
if(in_array("ubt", $words)
{
wordCount++;
}
}
}
I know about this,
if(Arrays.asList(words).contains("ubt"));
which basically converts the array into an List / ArrayList or whatever, however I want to treat this as an array only if possible.
An array is the wrong data structure; a Set is the weapon of choice:
Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
System.out.println("Enter your " + (count+1) + ": ");
words.add(sc.next());
}
if (words.contains("ubt"))
wordCount++;
}
The contains() method of a HashSet completes in constant time not matter how large the set is. Although performance is irrelevant for small input sizes like this usage, it's good to get in the habit of choosing the right tools for the job. It also makes your code cleaner.
Generally speaking, don't use arrays unless you absolutely have to; they are only rarely used in commercial code.
The simple solution
public static boolean contains(String toFind, String[] strings) {
for (String str : strings) {
if (str.equals(toFind)) return true;
}
return false;
}
EDIT:
To increase it after the user inputs a word, use this in the loop:
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
if (words[count].equals("ubt")) wordCount++;
You can just iterate over array
for (String str : array){
if(str.equals("ubt")){
wordCount++;
}
}
Edit:
It's just equivalent to a normal for loop
for(int i=0; i<array.length; i++) {
if(array[i].equals("ubt")){
wordCount++;
}
}
I have to first take as input the number of strings to be sorted. As they are entered, I have to sort them in ascending order, not at the end. The first part came out fine, but I don't know how to sort them (preferred method per instructor is the compareto method) when I have nothing to compare until it's entered. I cannot use the Arrays class or Collection class, which means I have to work around it to test my ingenuity.
Does anyone have any tips or pseudo code to lead me in the right direction?
Thanks.
Here is the code:
import java.util.*;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
String element_number = input.nextLine();
String[] user_word = new String[Integer.parseInt(element_number)];
for (int i = 0; i < Integer.parseInt(element_number); i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_word[i] = input.nextLine();
}
System.out.println();
}//end Main Method
}//end Class
I am supposed to sort these elements as they are put in, not after (which makes it even more difficult for me). I cannot use anything in the Arrays class or Collection class to sort them. They have to be sorted in ascending order. So, if a user types "4" as the number of elements, then types "Cherry, Banana, Orange, Apple," it will output: "Apple, Banana, Cherry, Orange."
Looks like you need Insertion Sort. Google it and try to understand the concept. Then try implementing it. Once you got that far you will probably have questions about specific parts where you struggle (if you'll struggle at all).
I got it and it worked as intended. It took some thinking, but it's done. I wanted to post my completed code for future questions from others.
import java.util.Scanner;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
int array_size = input.nextInt();
String[] user_words = new String [array_size];
input.nextLine();
for (int i = 0; i < user_words.length; i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_words[i] = input.nextLine();
}//end for
System.out.println();
sortStrings(user_words);
printTheArray(user_words);
}//end Main
public static void sortStrings(String[] words) {
/**
* This method will utilize an Insertion Sort Algorithm
*/
for (int i = 0; i < words.length; i++)
{
for(int j = i + 1; j < words.length; j++)
{
if(words[i].compareToIgnoreCase(words[j]) > 0)
{
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}//end if
}//end inner for
}//end outer for
}//end sortSTrings Method
public static void printTheArray(String[] the_words) {
/**
* This following code block will print the array, and format it properly
* so there is no comma after the last word in the array.
*/
if (the_words.length >= 1)
{
System.out.print(the_words[0]);
}
for (int i = 1; i < the_words.length; i++)
{
System.out.print(", " + the_words[i]);
}
}//end printTheArray Method
}//end Sort_As_Inserted Class
I'm trying to make a two dimensional array and output the results [3][3] in 3 lines and 3 colons,
but I get it like 123456789 in a straight line.
Now I know that I get this result because of the "println" command but I would like to know how can I get it work the way I want it to. Sorry, I'm new to programming.
import java.util.Scanner;
public class klasa {
public static Scanner lexo = new Scanner(System.in);
public static void main(String[]args){
int[][] array = new int[3][3];
for(int a=0;a<3;a++){
for(int b=0;b<3;b++){
System.out.println("Shkruaj numrat: ");
array[a][b]= lexo.nextInt();
}
}
for(int a =0; a<3;a++){
for(int b=0;b<3;b++){
System.out.println(array[a][b]);
}
}
}
}
You should try:
for(int a = 0; a < 3;a++){
for(int b = 0; b < 3;b++){
System.out.print(array[a][b] + " ");
}
System.out.println(); //new line
}
to make a new line only after three elements (and add spaces (optional)).
Hope this helps.
for(int a = 0; a<3; a++){
for(int b=0; b<3; b++){
System.out.print(array[a][b]);
System.out.print(" ");
}
System.out.println();
}
(That prints trailing spaces on each line, but it's a decent start.)
Use plain old print for each value, then print a newline after each row in your outer loop.
In general make your code reflect precisely what you are trying to do: Print each element in a row, followed by a newline. The computer generally follows your instructions to the letter.