Printing Two Dimensional Array - java
I am working in a small task that allow the user to enter the regions of any country and store them in one array. Also, each time he enters a region, the system will ask him to enter the neighbours of that entered region and store these neighbours.
I did the whole task but I have small two problems:
when I run the code, the program does not ask me to enter the name of the first region
(This is happened only to the first region)
I could not be able to print each region and its neighbours like the following format:
Region A: neighbour1 neighbour2
Region B: neighbour1 neighbour2
and so on.
My code is the following:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r+1) + ": ");
String region = kb.nextLine();
System.out.print("How many neighbors for region #" + (r+1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
kb.nextLine();
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #"
+ (n) + ": ");
regions[r][n] = kb.nextLine();
}
} else System.exit(0);
}
for(int i=0; i<REGION_COUNT; i++){
for(int k=0; k<2; k++){
System.out.println(regions[i][k]);
}
}
}
}
Thanks everybody for your immediate helps. But let me explain to you what I want in more details.
First of all, I need to use the two dimensional array.
Secondly, my problem now is just with the printing of the result. I want to print the results like the following format:
> RegionA : its neighbours
For example, let us take USA
> Washington D.C: Texas, Florida, Oregon
--------------------------------------------------------------------------
Dear ykartal,
I used your program and it gave me the following:
when I run the code, the program
does not ask me to enter the name of
the first region (This is happened
only to the first region)
Because you are using nextLine, program take your first edit for nextLine use next insteadof nextline
could not be able to print each region and
its neighbours like the following
format: Region A: neighbour1
neighbour2 Region B: neighbour1
neighbour2 and so on.
A and B is the name or Alphabetic order of regions? If alphabetics 65 is the aSCII equalence of 'A' and 66 is 'B' ... So using (char)65 write A. Otherwise put region names instead of (char)65+i
Try this;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[] regionNames = new String[REGION_COUNT];
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1)
+ ": ");
regionNames[r] = kb.next();
System.out
.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n)
+ ": ");
regions[r][n] = kb.next();
}
} else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(regionNames[i] +": ");
for (int k = 0; k < 2; k++) {
System.out.print(regions[i][k]+", ");
}
System.out.println();
}
}
}
Output;
Please enter the number of regions: 2
Please enter the name of region #1: aaa
How many neighbors for region #1: 1
Please enter the neighbour #0: a1
Please enter the name of region #2: bbb
How many neighbors for region #2: 2
Please enter the neighbour #0: b1
Please enter the neighbour #1: b2
aaa: a1
bbb: b1 b2
Note: This is not a good code, you must handle if user enter alfanumeric characters instead of numbers where you expected user will enter numeric values.
UPDATE:
This is what you want:
for (int i = 0; i < region.length; i++){
StringBuilder sb = new StringBuilder();
sb.append(region[i] + ": ");
for (int i2 = 0; i2 < neighbor.length; i2++){
if (i2 != 0 && i2 != neighbor.length-1){
sb.append(", " + neighbor[i2]);
}else{
sb.append(neighbor);
}
}
System.out.println(sb.toString());
}
I think it's going to be easier for you if you manipulate your information in a Map.
Try this
Map<String, List<String>> mapRegionNeighbor = new HashMap<String, List<String>>();
System.out.println("What region would you like to see?");
String regionName = scanner.nextLine();
List<String> neighborList = mapRegionNeighbor.get(regionName);
for(String neighbor : neighborList){
System.out.println(regionName + ": " + neighbor);
}
So, basically, if you want to add information to regions:
if it's a new region do this
mapRegionNeighbor.put(regionName, new ArrayList<String>);
if region has got a list of neighbor already, you'll do this to add a new neighbor:
List<String> neighborList = mapRegionNeighbor.get(regionName);
neighborList.add(neighborName);
mapRegionNeighbor.put(regionName, neighborList);
This 3 lines above will just update your region.
To run thru all values printing there neighbors, do something like this:
Iterator it = countedWords.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
for (String neighbor : pairs.getValue()){
System.out.println(pairs.getKey() + ": " + neighbor);
}
}
Related
Making a calculator that does operation of x number of numbers
package com.company; import java.util.*; import java.lang.*; public class ENCRYPTED { public static void main (String args[]) { //Declaring scanner Scanner sc = new Scanner(System.in); //Declaring Arrays double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",}; double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; //Getting Number of Numbers System.out.println(" How many numbers to add/subtract ? : "); int nofns = sc.nextInt(); // for loop that executes to get the numbers for (int i = 0; i < nofns; i++) { System.out.println("Enter Number " + i + " : "); numbers[i] = sc.nextDouble(); System.out.println("Enter Operator for number " + i + " : "); op[i] = sc.next(); ans[i] = numbers[i] + numbers[i+1]; System.out.println(ans[i]); System.out.println(numbers[i]); System.out.println(op[i]); } } } this is a program I made that takes in x numbers of numbers and stores them in the array (numbers) and operators (op). I want to store the operations done (-,+,*,/) on the ans array. I want to get a logic for this program that does the operations and stores them in the array. so these are my question. How do I write this Write this : (This taken from numbers array:5) ((This taken from op array)-) (This taken from numbers array:4) = (Stored and printed in ans aray)1 thanks for all for reading this EDIT: "I just discovered the method for adding and substracting but I still want to find the multiplication and division, Sorry for not commenting the code" THIS IS THE IMPROVED CODE package com.company; import java.util.*; import java.lang.*; public class ENCRYPTED { public static void main (String args[]) { //Declaring scanner Scanner sc = new Scanner(System.in); //Declaring Arrays double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",}; double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; double sum=0; //Getting Number of Numbers System.out.println(" How many numbers to add/subtract ? : "); int nofns = sc.nextInt(); // for loop that executes to get the numbers for (int i = 0; i < nofns; i++) { System.out.println("Enter Number " + i + " : "); numbers[i] = sc.nextDouble(); //Ex : 5 // System.out.println("Enter Operator for number " + i + " : "); // op[i] = sc.next(); //Ex: + System.out.println("Enter Number " + i + " : "); numbers[i+1] = sc.nextDouble(); //Ex : 6 ans[i] = numbers[i] + numbers[i+1]; System.out.println("Answer is " + ans[i]); if (i == nofns) { break; } } for(int i=0; i<nofns; i++){ sum = sum + ans[i]; } System.out.println("Elements of the sums are: "+Arrays.toString(ans)); System.out.println("Sum of the numbers :: "+sum); } } IF anyone can suggest the method for multiplication and division, thanks for the help "OUTPUT: Number one : 4 Number Two : -2 and : 2" NOTE: YOU NEED TO SUFFIX "-" SIGN BEFORE THE NUMBER TO SUBSTRACT IT
This looks like homework so I'll go at a high level. In general, you want to handle each of the 4 cases you have. Those cases are (+-*/) and maybe teh default case where you have invalid input. Then, based on what the value of op[i] you will perform the corresponding item instead of unconditionally adding like this: ans[i] = numbers[i] + numbers[i+1];
Can't find array value
Can someone help me with this problem. I have been given to do some coding exercise I need to do search Array problem Below is the output that i want : I have a problem where when I put the correct value it will not come out the output I want instead it will come out the output "Player not Found" so how to solve this. I feel like I missed something. Here my code: import java.util.Scanner; public class Main{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); System.out.println(" Welcome to VictoRoar Information System " ); System.out.println( " ********************"); System.out.print(" Enter n , number of player: "); int n = sc.nextInt(); //declare,initialize array String [] name = new String[n]; double [] height = new double[n]; sc.nextLine(); //put input in the array for (int i=0; i<n;i++) { System.out.print(" Enter player's name :" ); name[i] = sc.nextLine(); System.out.print(" Enter player's height (cm) :" ); height[i] = sc.nextLine(); } //search array System.out.print(" Write the player height that you want to know : "); double findheight=sc.nextDouble(); boolean noheight = false; for(int i = 0; i<n; i++) { if (n == height[i]) { noheight = true; System.out.println("Player name "+ name[i] + " with height " + height[i]+ " present at index " +i); } } if (noheight == false ) System.out.println("Player not found"); System.out.println("**********************"); } } I hope you guys can help me to solve this problem.
You have to use the findheight instead of n variable in your if (n == height[i]) condition: try this it's work : import java.util.Scanner; public class Main{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); System.out.println(" Welcome to VictoRoar Information System " ); System.out.println( " ********************"); System.out.print(" Enter n , number of player: "); int n = sc.nextInt(); //declare,initialize array String [] name = new String[n]; double [] height = new double[n]; sc.nextLine(); //put input in the array for (int i=0; i<n;i++) { System.out.print(" Enter player's name :" ); name[i] = sc.nextLine(); System.out.print(" Enter player's height (cm) :" ); height[i] = Double.valueOf(sc.nextLine()); } //search array System.out.print(" Write the player height that you want to know : "); double findheight=sc.nextDouble(); boolean noheight = false; for(int i = 0; i<n; i++) { if (findheight == height[i]) { noheight = true; System.out.println("Player name "+ name[i] + " with height " + height[i]+ " present at index " +i); } } if (noheight == false ) System.out.println("Player not found"); System.out.println("**********************"); } } result: Welcome to VictoRoar Information System ******************** Enter n , number of player: 2 Enter player's name :Alex Enter player's height (cm) :120 Enter player's name :David Enter player's height (cm) :122 Write the player height that you want to know : 120 Player name Alex with height 120.0 present at index 0 **********************
Have to design a lottery program that using Arrays and Arraylists that print results for the whole year
So I have to write a program that mimics Megabucks lottery game. It should either let the user enter 6 numbers OR automatically pick 6 numbers and 1 bonus number. The troubling part is that I have to design it in a way that it will produce 104 drawings(2 drawings a week for 52 weeks). I can't seem to write the code in a way that the 104 drawings are all randomized. Here's the code I have for drawing the 6 winning numbers and 1 bonus number: import java.util.*; public class oops { public static void main(String[] args) { Random randomGenerator = new Random(); int bonus = randomGenerator.nextInt(42)+1; List <Integer> winningNumbers = new ArrayList<Integer>(6); for(int i=0; i < 6; i++) { winningNumbers.add(randomGenerator.nextInt(42)+1); } System.out.println(); System.out.println("------------------------------------------------------------"); System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]"); System.out.println("------------------------------------------------------------"); } } And the output for that part is: As for my code for the rest of the program: public void getPlayNum() { Scanner scan = new Scanner(System.in); System.out.println(" Enter 1 for manual picking or 2 for automatic: "); int input = scan.nextInt(); List <Integer> playNumbers = new ArrayList<Integer>(); if(input == 1) //let user pick out their own play numbers { for(int i =0; i< 6; i++) { System.out.println("Enter number 1 and 42 (no duplicates): "); int userNum = scan.nextInt(); if(playNumbers.contains(userNum)) { System.out.println(); System.out.println("*** DUPLICATE FOUND! Please enter a non-repeating digit between 1 and 42 ***"); i--; System.out.println(); }else if (userNum > 42 || userNum < 1) { System.out.println(); System.out.println("*** OUT OF RANGE! Please enter a non-repeating digit between 1 and 42 ***"); i--; System.out.println(); }else{ playNumbers.add(userNum); System.out.println("Here are your numbers: "); System.out.println(Arrays.toString(playNumbers.toArray())); } } }else{ Random randomGenerator = new Random(); for (int index = 0; index < 6; index++) { playNumbers.add(randomGenerator.nextInt(42)); } System.out.println(); System.out.println("Here are the numbers randomly generated for you: "); System.out.println("------------------------"); System.out.println(Arrays.toString(playNumbers.toArray())); System.out.println("------------------------"); System.out.println(); } } Nothing is properly formatted but I need to fix the important parts first. Thanks for any tips at all!
It is as easy as #Gendarme mentioned: for(int draw = 0; draw < 104; draw++) { int bonus = randomGenerator.nextInt(42)+1; List <Integer> winningNumbers = new ArrayList<Integer>(6); for(int i=0; i < 6; i++) { winningNumbers.add(randomGenerator.nextInt(42)+1); } System.out.println(); System.out.println("------------------------------------------------------------"); System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]"); System.out.println("------------------------------------------------------------"); }
Java program keeps exiting program prematurely
I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...". Knowing me it's probably something simple, but I cannot figure this one out. import java.util.*; public class hw1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please indicate the number of states"); int numState = input.nextInt(); int[] state = new int[numState]; boolean[] accept = new boolean[numState]; for (int i = 0; i < numState; i++) { System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)"); int finalState = input.nextInt(); if (finalState == 1) accept[i] = true; } // for System.out.println("Enter the number of symbols s: "); int numSym = input.nextInt(); int[][] next = new int[numState][numSym]; for (int i = 0; i < numState; i++) { for (int j = 0; j < numSym; j++) { System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j); next[i][j] = input.nextInt(); }//nested for }//for String digits = input.nextLine(); System.out.print("Enter a string of digits (0-9) without spaces to test:"); int[] digitArray = new int[digits.length()]; for (int i = 0; i < digits.length(); i++) { digitArray[i] = digits.charAt(i); } for (int i = 0; i < digits.length(); i++) { System.out.print(digitArray[i] + " ,"); } System.out.println("end of program"); }// main; }// class
Change your code to : input.nextLine(); System.out.print("Enter a string of digits (0-9) without spaces to test:"); String digits = input.nextLine(); This will get and ignore the newline character left in the stream after call to nextInt()
Arrays showing vertically instead of horizontally
I am sort of new to programming and I am working on a school assignments on arrays I am suppose to write a program that stores statistics using arrays. import java.io.*; public class HockeyLeague { static final int Rows = 7; static final int Cols = 8; static double HockeyChart [][] = new double[Rows][Cols]; static HockeyLeague HL = new HockeyLeague(); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[])throws IOException { while(true){ System.out.println("Welcome to the NHL statistic program"); System.out.println("Would you like to proceed to the program? <y for yes, n for no>"); final String menuDecision = br.readLine(); if (menuDecision.equals("n")) { System.out.println("Goodbye"); System.exit(0); } if (menuDecision.equals("y")) { while(true) { System.out.println("The 8 teams are Toronto Maple Leafs, Montreal Canadiens, Ottawa Senators, Detroit Red Wings, Boston Bruins,"+ " Chicago Blackhawks, New York Islanders, and Pitsburg Penguins"); System.out.println("To input statistics for Toronto, enter '0' "); System.out.println("To input statistics for Montreal, enter '1' "); System.out.println("To input statistics for Ottawa, enter '2' "); System.out.println("To input statistics for Detroit, enter '3' "); System.out.println("To input statistics for Boston, enter '4' "); System.out.println("To input statistics for Chicago, enter '5' "); System.out.println("To input statistics for New York, enter '6' "); System.out.println("To input statistics for Pitsburg, enter '7' "); int numString = Integer.parseInt(br.readLine()); Info (numString); } } } } public static double[][] Info(int teamInput)throws IOException{ System.out.println("Enter the amount of games played"); int games = Integer.parseInt(br.readLine()); HockeyChart [0+teamInput][1] = games; System.out.println("Enter the amount of wins"); int wins = Integer.parseInt(br.readLine()); HockeyChart [0+teamInput][2] = wins; System.out.println("Enter the amount of ties"); int ties = Integer.parseInt(br.readLine()); HockeyChart [0+teamInput][3] = ties; System.out.println("Enter the amount of losses"); int losses = Integer.parseInt(br.readLine()); HockeyChart [0+teamInput][4] = losses; System.out.println("Enter the amount of goals scored"); int goals = Integer.parseInt(br.readLine()); HockeyChart [0+teamInput][5] = goals; for (int i = 0; i < Rows; i ++) { for (int j = 0; j < Cols;j ++) { System.out.println(HockeyChart[i][j] + " "); } System.out.println(" "); } return HockeyChart; } } This is the program I came up with. I dont understand why I get an output that is a long vertical row of numbers instead of row of numbers side by side. Any help would be appreciated! thanks
In your Info method, while iterating over arrays, you are using System.out.println(), instead of that you will need to use System.out.print() method. for (int i = 0; i < Rows; i ++) { for (int j = 0; j < Cols;j ++) { System.out.print(HockeyChart[i][j] + " "); } System.out.println(); } Second println statement will help you to move to next line after one row is printed.
Take a look at your loop: for (int j = 0; j < Cols;j ++) { System.out.println(HockeyChart[i][j] + " "); } println is short for Print Line - it prints the given string, and then moves on to the next line. If you want to print all the contents of the array in a single line, you could use System.out.print instead: for (int j = 0; j < Cols;j ++) { System.out.print(HockeyChart[i][j] + " "); }
You are using System.out.println which means print in new line. You can use System.out.print for same line i.e horizontal row. Code will be like this for (int i = 0; i < Rows; i ++) { for (int j = 0; j < Cols;j ++) { System.out.print(HockeyChart[i][j] + " "); } System.out.println(" "); } return HockeyChart;