0
How do access array using scanner im unsure what i put in println() method. Thanks
import java.util.*; public class Program { public static void main(String[] args) { Scanner x = new Scanner(System.in); int y = x.nextInt(); int [][] z = {{1,2,3},{4,5,6}}; System.out.println(); } }
4 Answers
+ 2
I don't understand.
You want to print the entire array? Or, just a value?
You put in the parenthesis of print() whatever you want to print to the console.
So,
System.out.println(z[1][1]);
// Output: 5
So to print everything you'd use 2 for loops. One for each array, the other for each element in that array. (In simpler words, one for the columns, one for the rows).
+ 2
Hm..
Like litteraly input that word for word?
It certainlly can be done, but may get messy.
Lets break it down.
"using scanner [1][1]"
The only thing that actually matters here is [1][1].
If you want using scanner to be some kind of keyword: depending on how advanced you want this, you can do something like this:
Keep in mind this is a simple version. It can be heavily improved, I'm just writing it here in hopes you can get the idea. I'm also writing this on phone, let me know if there's mistakes. You should also check if the index is out of bounds (which I didn't do). Probably also better to use StringBuilder.
public static void main(String[] meatBall){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// scanner is "sc"
// User wants to use the scanner
if(input.contains("using scanner"))
scannerCall(input.replace("using scanner"), "");
}
// separate method
static void scannerCall(String indexs){
indexs = indexs.replaceAll("\\s","");Â
// remove spaces
//Now we need to get the ints from [1][1]
int col = Integer.parseInt(""+indexs.charAt(indexs.indexOf("[")+1));
indexs = indexs.replace("["+col+"]", "");
// remove first [1] from string
int row = Integer.parseInt(""+indexs.charAt(indexs.indexOf("[")+1));
// Now we have everything we need
int[][] array = {{5,1},{1,3}};
System.out.println(array[col][row]);
}
Now if I input "using scanner [1][0]" the output should be: 1.
Which is exactly as it should be in the array. đ
0
sorry, i want to use scanner to output the value?
so when i input "using scanner" [1][1] the output will be 5?
can this be done?
0
sorry faith i dont think i explained my self propley i eventually figured out what i needed to do i will try and add another array tommrow thanks.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
int [] array = {10, 5, 7, 2};
System.out.println("Choose a value between 0-4 inside array");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int value = array[num];
System.out.println(value + " < Your selected Value");
}
}