String [][] Output issues - java

I am trying to write a program that i need to output a 2 dimensional array for a list of first and last names entered by the user. When I try running the program there is no errors, but it gives me this for output:
[[Ljava.lang.String;#b8f82d, [Ljava.lang.String;#1ad77a7,
[Ljava.lang.String;#18aaa1e, [Ljava.lang.String;#a6aeed,
[Ljava.lang.String;#126804e, [Ljava.lang.String;#b1b4c3,
[Ljava.lang.String;#d2906a, [Ljava.lang.String;#72ffb,
[Ljava.lang.String;#1df38fd, [Ljava.lang.String;#16a786,
[Ljava.lang.String;#1507fb2, [Ljava.lang.String;#1efb836,
[Ljava.lang.String;#126e85f, [Ljava.lang.String;#161f10f,
[Ljava.lang.String;#1193779, [Ljava.lang.String;#8916a2,
[Ljava.lang.String;#2ce908, [Ljava.lang.String;#77158a,
[Ljava.lang.String;#27391d, [Ljava.lang.String;#116ab4e,
[Ljava.lang.String;#148aa23, [Ljava.lang.String;#199f91c,
[Ljava.lang.String;#1b1aa65, [Ljava.lang.String;#129f3b5,
[Ljava.lang.String;#13f3045, [Ljava.lang.String;#17a29a1,
[Ljava.lang.String;#1434234, [Ljava.lang.String;#af8358,
[Ljava.lang.String;#d80be3, [Ljava.lang.String;#1f4689e,
[Ljava.lang.String;#1006d75, [Ljava.lang.String;#1125127,
[Ljava.lang.String;#18dfef8, [Ljava.lang.String;#15e83f9,
[Ljava.lang.String;#2a5330]
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code:
package assignment_6_1;
import java.util.Scanner;
import java.util.Arrays;
public class Assignment_6_1 {
public static void main(String[] args) {
//Create a Scanner
Scanner input = new Scanner(System.in);
//Create int & string []
String[][]firstAndLastNames = new String[36][2];
int[]heightOfPerson = new int[36];
//Gather list of names and heights
for(int i=0; i<heightOfPerson.length; i++)
{
//Get first name
System.out.println("Enter Your First Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[1][i] = input.next();
//Get last name
System.out.println("Enter Your Last Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[2][i] = input.next();
//Get height in inches
System.out.println("Enter your height (Iches) " + "Passenger #" + i+1 + ": ");
heightOfPerson[i] = input.nextInt();
if(firstAndLastNames[36][2] != null){
System.out.println(Arrays.deepToString(firstAndLastNames));
break;}
}
}
}
I then have to output the height of the person but I have not gotten that far yet.

Don't use Arrays.toString(array). Use Arrays.deepToString(array). It will print multi-dimensional arrays.
String[][] array = new String[][] {
{ "Apple", "Pear", "Fruit" },
{ "Pi", "Rho", "Omega" },
{ "Jack", "Jill", "Joe" }
};
System.out.println(Arrays.deepToString(array));
//Prints: [[Apple, Pear, Fruit], [Pi, Rho, Omega], [Jack, Jill, Joe]]

Maybe you should not do
for(int i=0; i>35; i++)
but rather
for(int i=0; i<35; i++)

You are stringifying the outer array, but the inner arrays are not handled. What you need to do is to build the output by iterating over the outer array.
This should help:
for (String[] firstAndLastName : firstAndLastNames) {
System.out.println(firstAndLastName[0] + ", " + firstAndLastName[1]);
}
Alternatively you can store the user details in a User object. Then, if you define a toString method on that object thhe original Arrays.toString call will produce more legible output.
class User {
private String firstName, lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
...
public String toString() {
return firstName + ", " + lastName;
}
}
Also, as nielsen points out your for loop has the wrong loop test on it. You have an empty array at the moment so you need to address that as well.

Answer by matthew is perfect but if we do small change in concat operation then it will become more fluent for eg.
public static void main(String...args) {
String[][] firstAndLastName = {
{"Bob","Martin"},
{"Martin","Fowler"}
};
for(String[] name : firstAndLastName) {
System.out.println(toString(name));
}
}
private static String toString(String[] a) {
int iMax = a.length - 1;
StringBuilder b = new StringBuilder();
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.toString();
b.append(", ");
}
}

You are trying to store the last name in a place that does not exist in your array!
You are declaring your array like this:
String[][]firstAndLastNames = new String[35][1];
This means you have 35 rows, and 1 column. Arrays start at index zero. Not one.
When you are trying to store your last names:
firstAndLastNames[i][1] = input.next();
You are not calling the correct column index. Change the array delcaration line line to this:
String[][]firstAndLastNames = new String[35][2]; //now we have 2 columns
Once you store the data correctly, you need to iterate through the array to properly display your data.
try the following code:
public static void main(String[] args) {
String[][] array = new String [3][2]; //Notice how the column declaration is now '2'. This means available indexes are 0 and 1.
Scanner scn = new Scanner (System.in);
for (int i = 0; i < array.length; i++) {
System.out.println ("Enter data " + i + ")");
array[i][0] = scn.nextLine();
}
array[0][1] = "1"; //Understand why this works now?
array[1][1] = "2";
array[2][1] = "3";
for (int i = 0; i < array.length; i++) {
for (int k = 0; k < 2; k++) {
System.out.println((array[i][k]));
}
}
}

Related

Want to print my stored names in array by JoptionPane, JAVA

public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}

while loop with store value for next while loop in java

I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}

Printing out elements at certain indexes in vectors in Java

This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}

Basic Arrays in a Java Program

I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}

Wrong return type in method

I need to make a program that adds long integers without using the biginteger class.
I am working on the add method now and I think I have it correct but I am stuck on returning the correct data type for my method and I'm not sure how to correct it.
Here are my 2 classes so far:
Main Class:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
LargeInteger.class:
public class LargeInteger
{
private int[] intArray;
//convert the strings to array
public LargeInteger(String s)
{
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++)
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
//display the strings
public String display()
{
String result="";
for (int i = 0; i < intArray.length; i++)
result += intArray[i];
return result.toString();
}
//get first array
public int[] getIntArray()
{
return intArray;
}
public LargeInteger add(LargeInteger secondInt)
{
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++)
{
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
return resultArray;
}
}
You need a second LargeInteger constructor:
public LargeInteger( int[] array ) {
intArray = array
}
Then your method can return:
return new LargeInteger( resultArray );
Well first thing, your method add in LargeInteger is supposed to return a LargeInteger, but instead returns an array (int[]). You could fix this by adding a constructor for LargeInteger that takes in an int[] parameter (i.e. LargeInteger(int[] digitArray)). Then, in your add method you could simply do: return new LargeInteger(resultArray);.

Categories