Two dimensional array in Java - java

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.

Related

How to print array index number?

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.

Why is this simple program not working

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 need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

I have a working program which takes the first letter of a word then switches it to the back of the word and adds "ay to the end. It works fine but I am trying to store the original word and the newWord in a 2D array and output all contents of the array. I have tried but have come to a dead end.
import javax.swing.JOptionPane;
public class Decoder1App{
public static void main(String[]args){
String word="";
String newWord="";
String log[][] = new String[3][2];
for(int i=0;i<log.length;i++){
for(int j=0;j<log[i].length;j++){
Decoder1 D1 = new Decoder1();`enter code here`
word = JOptionPane.showInputDialog(null,"Please enter your word");
D1.setWord(word);
D1.compute();
newWord=D1.getNewWord();
}
}
JOptionPane.showMessageDialog(null,"The new word is " + newWord);
}
}
What exactly doesn't work?
Why are you using a 2d array?
If you must use a 2d array:
int numOfPairs = 10;
String[][] array = new String[numOfPairs][2];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
array[i] = new String[2];
array[i][0] = "original word";
array[i][1] = "rearranged word";
}
}
Does this give you a hint?

Using nested for loops to create a triangle with asterisks

using nested for loops statements to draw triangles of ""s. The number of ""s on the last row is input from the user (valid range: 5 to 21). the out put should look like this:
Sample output:
How many stars/last row (5-21)? 25
Out of range. Reenter: 7
*
**
***
****
*****
******
*******
so far this is what i have for the code. I don't know how to get it to look like a triangle. any help would be great.
import java.util.Scanner;
public class Lab7_2{
public static void main(String[] args){
//declarations
Scanner input= new Scanner(System.in);
int how_many;//num of triangles
int m; //constant
int c;//constant
int rows;//row
//prompt for input
System.out.println("Drawing triangles program.");
System.out.println("==============================");
System.out.println("How many triangles?");
how_many=input.nextInt();
System.out.println("How many stars/last row (5-21)?");
rows=input.nextInt();
while(rows<=5||rows>=21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*");
System.out.println();
}
}
}
}
To center a line, use this:
private static String center(String line, int length) {
StringBuilder newLine = new StringBuilder();
for (int i = 0; i < (line.length() - length)/2; i++)
newLine.append(" ");
}
newLine.append(line);
return newLine.toString();
}
Also,
System.out.println();
prints a line break after each string, which is not what you intend.
Fixed code:
private void printTriangle(int base) {
StringBuilder currentStars = new StringBuilder();
for (int currLine = 1; currLine < base; currLine++) {
currentStars.append("*"); // Don't create a new String, just append a "*" to the old line.
//if (currLine % 2 == 1)
// System.out.println(center(currentStars.toString(), base)); // For centered triangle
System.out.println(currentStars.toString()); // For non-centered triangle
}
}
You are using a println statement to print your stars, as such each will be on its own line no matter what
System.out.println("*");
You want a print statement instead
System.out.print("*");
Additionally inside the star printing loop you have an extra System.out.println(); putting a blank line in, that should be outside the inner for loop
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*"); <-- println always starts a new line, should be print
System.out.println(); <--- shouldn't be within inner loop
}
<--- println() should be here to advance to the next line of stars
}
println() always starts a new line after the output. Try print instead and then one println() after the inner loop.
Just fix your for loop as
for (m = 1; m <= rows; m++) {
for (c = 1; c <= m; c++) {
// first print the * on the same line
System.out.print("*");
}
// then move to the next line
System.out.println();
}
Notice, that you need to use System.out.print() (that does not write a new line \n to the output stream) for the asterisks * to get printed on the same line.
I believe this is the most efficient and simple way to do it, saves having to call the print/println method hundreds of times when playing with larger pyramids.
String out;
for (m = 0; m < rows; m++) {
out = "";
for (c = 0; c < m; c++) {
out+="*";
System.out.println(out);
}
}
Basicly your string is "", and you add a "*" after every time you print it to the next line.

how to store a text file into an array and count how many words are in it

I was given a homework in which I need to count the number of words in a file and output how many words are the same. Like "a" in the whole text maybe it was repeated 350 times. I hope you get my point.
Now, im trying to do some tests and created a file("test.txt") containing:
Im a good boy
Hello World
A happy world it is
What I'm trying to do is storing it into an array to be able to count the words in the file. But I'm having a hard time. This is what i got so far.
void readFile() {
System.out.println("Gi navnet til filen: ");
String filNavn = sc.next();
File k = new File(filNavn);
try {
Scanner sc2 = new Scanner(k);
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String[] m = line.split(" ");
String x = m[0];
System.out.println(x);
}
} catch (FileNotFoundException e) {
System.out.print("mmm");
}
}
but this only outputs the first words on the line.
What I would like to see is the same as the text file. But stored in an array. How can I do it?
Im a good boy
Hello World
A happy world it is
This will only print out the first word because of this
String[] m = line.split(" ");
String x = m[0];
System.out.println(x);
Here you are only assigning the first word in the array (created by your split) to the variable x and then printing only that word.
To print all the words you will need to loop the array like so
for(int i = 0; i < m.length; i++)
{
System.out.println(m[i]);
}
And to print the same as the file you could use System.out.print(). Note you will need to put the spaces back in and also account for the new lines. Below is one approach:
for(int i = 0; i < m.length; i++)
{
if(i == m.length - 1)
System.out.print(m[i] + "\n");
else
System.out.print(m[i] + " ");
}
Since your post didn't say you HAD to do it in Java (although I am guessing that is the case), I offer this:
perl -e 'while(<STDIN>) { map { $w->{lc($_)}++; } split("\\s", $_); } map { print "$_ $w->{$_}\n"; } keys %{$w} ;' < test.txt

Categories