Input and storing Strings in multi-dimensional arrays with user-input
i have learned multidimensional array from google, it was easy to learn but when i have to implement in any scenerio! its difficult to handle it. i have declared multi-dimensional array using user input and now i want to declare this array in table . how?
import java.util.Scanner;
public class RugbyProject{
final static int RESULT_POINTS_WIN = 2;
final static int RESULT_POINTS_DRAW = 1;
final static int RESULT_POINTS_LOSS = 0;
final static int GAME_POINTS_TRY = 5;
final static int GAME_POINTS_PENALTY = 3;
final static int GAME_POINTS_DROP_GOAL = 3;
final static int GAME_POINTS_CONVERSATION = 2;
public class Stats {
// TODO Auto-generated method stub
int wins;
int draws;
int losses;
int tries;
int penalties;
int dropgoals;
int conversation;
int totalResultPoints = (wins * RESULT_POINTS_WIN) + (draws * RESULT_POINTS_DRAW) + (losses + RESULT_POINTS_LOSS) + (tries * GAME_POINTS_TRY) +
(penalties * GAME_POINTS_PENALTY) + (dropgoals * GAME_POINTS_DROP_GOAL) + (conversation * GAME_POINTS_CONVERSATION) ;
int averageScorePerMatch = (totalResultPoints/5);
}
public static void main(String args[]){
String teams[] = {"Ireland","England","Scotland","Brazil","Irelan","Romania","Germany"};
System.out.println("Welcome to the six nation ChampionShip");
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
Scanner myScanner = new Scanner(System.in);
int [] integer = new int[3];
for(int i = 0; i<3; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
Scanner myScanner2= new Scanner(System.in);
int[] integers2 = new int[3];
for(int i=0; i<3; i++){
integers2[i] = myScanner2.nextInt();
}
}
}
}
So far, I'm just trying to get the input and store it.I am new in java so i am not good in programming
Thats the answer to print array in table
public static void main(String args[]){
String teams[] = {"Ireland","England"};
int [] integer ={};
int[] integers2 ={};
int a=0; int b=3;
System.out.println("Welcome to the six nation ChampionShip");
integer = new int[6];
integers2 = new int[6];
Scanner myScanner = new Scanner(System.in);
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
//Scanner myScanner = new Scanner(System.in);
System.out.println("a="+a +" b="+b);
for(int i = a; i<b; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
//Scanner myScanner2= new Scanner(System.in);
for(int i=a; i<b; i++){
integers2[i] = myScanner.nextInt();
}
a=3;
b=6;
}
System.out.println("Team \tP \tW \tD \tL \t");
for(int j=0; j<teams.length; j++){
//
if(j==0){
System.out.println(teams[j]+"\t"+(integer[j]+integer[j+1]+integer[j+2])+"\t"+integer[j]+"\t"+integer[j+1]+"\t"+integer[j+2]);
}else{
System.out.println(teams[j]+"\t"+(integer[j+2]+integer[j+3]+integer[j+4])+"\t"+integer[j+2]+"\t"+integer[j+3]+"\t"+integer[j+4]);
}
}
Related
import java.util.Random;
import java.util.Scanner;
public class LuckyForLife {
public static int randomNum(int min, int max){
Random lotterynum = new Random();
int randomNum = lotterynum.nextInt((max-min)+1)+min;
return randomNum;
}
//**********************************************
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
//**********************************************
public static void main(String args[]) {
final String TITLE = "Lucky For Life Lottery";
final String CONTINUE_PROMPT = "Do this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
for(int counter=1; counter<=5; counter++) {
System.out.printf("Your Lucky For Life Cash numbers are: " + randomNum(1,43));
System.out.println(" Your Lucky Ball number is: " + randomNum(1,43));
}
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
}
I am trying to get all the random values to print on one line so it looks like a list rather than the program executing 5 times.
(Ex: Your numbers are 5, 10 , 15, 34, 41)
You may use an array to store the random numbers, then use a StringBuilder to build the final sentence :
public static void main(final String args[]) {
final String TITLE = "Lucky For Life Lottery";
final String CONTINUE_PROMPT = "Do this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
int totalNumbers = 5;
int[] numbers = new int[totalNumbers];
do {
for (int counter = 0; counter < totalNumbers; counter++) {
numbers[counter] = randomNum(1, 43);
}
StringBuilder builder = new StringBuilder();
builder.append("Your Lucky For Life Cash numbers are: ");
for (int number : numbers) {
builder.append(number);
builder.append(' ');
}
System.out.println(builder);
System.out.println("Your Lucky Ball number is: " + randomNum(1, 43));
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
I changed a little your code, take a look if this would work for your need.
import java.util.Random;
import java.util.Scanner;
public class LuckyForLife {
private static final String TITLE = "Lucky For Life Lottery";
private static final int MIN_RANDOM_INT = 1;
private static final int MAX_RANDOM_INT = 43;
public static void main(String[] args) {
System.out.println("Welcome to "+ TITLE);
String continueAnwser = "Y";
Scanner inputUser = new Scanner(System.in);
try {
while ("Y".equalsIgnoreCase(continueAnwser)) {
System.out.println("How many number do you wish to generate?");
int numberOfElementsTogenerate = inputUser.nextInt();
String randomNumbers = generateRandomNumbersAsString(numberOfElementsTogenerate);
System.out.println("Your Lucky Ball number is:"+ randomNumbers);
System.out.println("Do this again? [y/N]:");
continueAnwser = inputUser.next();
}
System.out.println("Thank you for using " + TITLE);
} finally {
if (inputUser != null) {
inputUser.close();
}
}
}
private static String generateRandomNumbersAsString(int numberOfElementsTogenerate) {
Random random = new Random();
StringBuilder numersGeneratedBuider = new StringBuilder();
numersGeneratedBuider.append("[");
for (int i = 0; i < numberOfElementsTogenerate; i++) {
numersGeneratedBuider.append(random.nextInt((MAX_RANDOM_INT - MIN_RANDOM_INT) + 1) + MIN_RANDOM_INT);
if (i < numberOfElementsTogenerate-1) {
numersGeneratedBuider.append(",");
}
}
numersGeneratedBuider.append("]");
return numersGeneratedBuider.toString();
}
}
I am new to java programming. I am trying to convert an string variable with array to an int variable array
but i have 2 errors and have no idea to fix it,
any help would be great, thanks..
This is my source code :
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int sum=0;
for(x=0;x<=1;x++)
{
System.out.print("input number : ");number[x]=in.next();
int value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum+number[x];
}
for(x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
This is what the errors look like
when you convert an array of stirngs to an array of integers,
we should have an array of integers declared
and in the code that you posted there are some syntax errors because you didnt declare integer array before use(int value[x])
and try the below code which will convert string array of numbers(string number[]) into an ineger array of numbers(int value[])
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100]; // here I declared an array of integers with the name value
int sum=0;
for(int x= 0;x <= 1; x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum + value[x];
}
for(int x=0; x<=1; x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
Use in.nextInt() method.
Scanner in = new Scanner(System.in);
int number[] = new int[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {`enter code here`
System.out.print("input number : ");
number[x] = in.nextInt();
sum = sum + number[x];
}
System.out.println("Sum :\t " + sum);
in.close();
}
Create a int array, then use it. int value[x]= Integer.parseInt(number[x]); is an error because your are trying to assign an integer to an array.
Correct one may be...
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100];
int sum=0;
for(int x=0;x<=1;x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]);
sum=sum+value[x];
}
for(int x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
There seems problem with declaration and usage of variable in you sample code.
Variable x is not initialzed
An integer value is assigned to and array declaration.
Try the below code to solve your issues.
import java.util.Scanner;
public class stringtoint {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {
System.out.print("input number : ");
number[x] = in.next();
int value = Integer.parseInt(number[x]);
sum = sum + value;
}
for (int x = 0; x <= 1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
in.close();
}
}
public static void main(String args[]) {
String[] exampleOfStringArray = {"11", "22", "33"/*, "ab", "cd", "ef", "", null*/};
int[] intArray = getIntArray(exampleOfStringArray);
int sum = getSumOf(exampleOfStringArray);
}
private static int[] getIntArray(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).toArray();
}
private static int getSumOf(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).sum();
}
Try below code, it is working.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
int noOfInputs = 2;
int value[] = new int[noOfInputs];
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.print("input number : ");
number[x] = in.next();
value[x] = Integer.parseInt(number[x]);
sum = sum + value[x];
}
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
}
I have an assignment, I was wondering how I could go about using 2D arrays with another class, I have a class called Die that looks like this:
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now in a main method i have to do the following
I have all the other parts done, I just cant seem to figure out this part.
My current code(Not started this part) is below
import java.util.Arrays;
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
String[] playerNames = new String[playerCount];
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();
}
int randomNum = (int)(Math.random() * (30-10)) +10;
}
}
Do any of you java geniuses have any advice for me to begin?
Thanks!
Here is your main method, you just need to update your main method with this one,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
HashMap<String, ArrayList<Die>> hashMap = new HashMap<String, ArrayList<Die>>();
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
hashMap.put(scan.nextLine(),new ArrayList<Die>());
}
for(String key : hashMap.keySet()){
System.out.println(key + "'s turn....");
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
hashMap.get(key).add(d);
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(hashMap.get(key).size()>4){System.out.println("Sorry, Maximum 5-Try you can...!!!");break;}
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
hashMap.get(key).add(dd);
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
for(String key : hashMap.keySet()){
System.out.println(key + " - " + hashMap.get(key));
}
}
EDITED
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++){
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(totalRollDie < 5){ // if user want one more time to roll die then first check whether alread user has rolled 5-time or not.
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ; // rolled and print whatever value get..
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++){
finalDie[i][var] = tempDie[var]; // store Die object into finalDie array which can random number for all user..
}
}
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i]){
System.out.println(de);
}
}
tempDie = null;
}
I've been working on this for a while but can't seem to get it. I need to store user input into an array from another object but I can't get it to work. I'm not sure if its my constructor or I'm missing something but any help is appreciated
Here is the output program
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps = new Polygon(side);
}
ps = new Polygon(side);
Here is the constructor of the other class
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
you need to do
ps=new Polygon(numSides+1); //adding 1 because for-loop starts with index 1
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps[i]=side;
}
by this what we do is assign the 'side' value entered by user to a particular index in array.
hope this helps!
Good luck
The way I understand your Program I think you are looking for this kind of logic
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side = 0;
Polygon ps;
int sideLengths[] = new int[numSides];// array to store length of polygon of sides `numSides`
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
sideLengths[i-1] = sc.nextInt();// creating array to store lengths
}
ps = new Polygon(sideLengths);// generating your pollygon by sending the array
}
And you Polygon class should look like this
class Polygon {
protected int[] sideLengths;// storing the lengths of all sides
public Polygon(int dimensions[]) {
sideLengths = dimensions ;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if(in.equalsIgnoreCase("p")) {
Integer sides[];
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
if(numSides>0){
sides = new Integer[numSides];
}
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
sides[i] = side;
}
ps = new Polygon(sides);
}
}
public class Polygon {
private Integer[] sides;
public Polygon(Integer[] sides){
this.sides = sides;
}
}
Now we have created an array of size of sides and array is been passed as an argument to constructor for initializing Polygon's object
it should be like
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps = new Polygon(numSides);
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps.addSide(side, i-1);
//ps = new Polygon(side);
}
//ps = new Polygon(side);
}}}
and Polygon class like
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
public void addSide(int side, int index){
sideLengths[index] = side;
}
}
You are calling the constructor correctly, but after for loop ends you are again creating a new instance of Polygon and assigning it to ps. Either create an array of int or ArrayList of Integer, and store each instance of Polygon side length in that just before the for loop ends.
ArrayList<int> psListpsSideLengthList = new ArrayList<int>;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
psListpsSideLengthList.add(side);
}
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();