package jellyProblem;
import java.util.*;
public class jellyProblem {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
String [] name =new String [100];
int [] volume=new int[100];
while(true){
if (studentNumbers==0)
break ;
else
for(int i=0;i<studentNumbers;i++){
name[i]=input.next();
int length =input.nextInt();
int width =input.nextInt();
int height =input.nextInt();
System.out.printf("\n%s %d %d %d\n",name[i],length,width,height);
volume[i]=length*height*width;
}
int minimum=0,maximum=0;
for(int i=1;i<studentNumbers;++i){
if (volume[i]<volume[minimum])
minimum=i;
if (volume[i]>volume[maximum])
maximum=i;
}
if(volume[minimum]==volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n",name[minimum],name[maximum]);
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
First request I don't know how to:
Prevent string duplicates in names[] array like
I want to stop array if characters of name[] is more than past (names[i].length<=10) it doesn't work with me
Maybe you can do it like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
List<String> names = new ArrayList<String>();
int[] volume = new int[100];
// clear all data to make it clean
names.clear();
while (true) {
if (studentNumbers == 0)
break;
else
for (int i = 0; i < studentNumbers; i++) {
String studentName = input.next();
// here is how prevent string duplicates in names[] array like
if (names.contains(studentName)) {
continue;
}
if (studentName.length() > 10) {
break;
}
names.add(studentName);
int length = input.nextInt();
int width = input.nextInt();
int height = input.nextInt();
System.out.printf("\n%s %d %d %d\n", names.get(i), length, width, height);
volume[i] = length * height * width;
}
int minimum = 0, maximum = 0;
for (int i = 1; i < studentNumbers; ++i) {
if (volume[i] < volume[minimum])
minimum = i;
if (volume[i] > volume[maximum])
maximum = i;
}
if (volume[minimum] == volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n", names.get(minimum), names.get(maximum));
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
a. Instead of using an Array of string you can use an ArrayList. The ArrayList will give you the power to perform various function over the list of String. Incase you want to write your own method and only allow non duplicates to be inserted into the Array then u can iterate over the array and check whether you encounter the same value. eg.
String newName = input.nextLine();
boolean checkDuplicate = dupliacteFunction(newName,name);
boolean dupliacteFunction(String newName , String []nameArray) {
for(String nameValue : nameArray) {
if(newName .equals(nameValue))
return true;
}
else return false;
}
b. String newName = input.nextLine();
newName.length();// This will give u the size of the string being read.
Please try and implement these changes and then we can suggest further alternatives. Happy Coding!!!
To answer your first question, there is no real way to prevent duplicates in an array. I would use an ArrayList object. If it is absolutely impossible to use an ArrayList, you could create a method like this:
public static String[] removeDupes(String[] array){
ArrayList<String> uniqueItems = new ArrayList<String>();
for(String s : array){
if(uniqueItems.contains(s) == false)
uniqueItems.add(s);
}
array = uniqueItems.toArray(array);
return array;
}
And to answer your second question, I don't know what you mean by "stop array" but it seems like all you need is a simple if-statement with exactly the condition you described.
Related
I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class
//Remove Method
public static int[] remove(int[]a){
int [] x = new int[a.length - 1];
for(int i = 1; i <= x.length; i++) {
x[i-1] = a[i];
}
return x;}
IsUniqueMethod to check uniqueness of Passed int
public static boolean isUnique(int []x, int n) {
if(x.length == 1) {
return true;}
else {
if(x[0] != n) {
return isUnique(remove(x), n);
}
else {
return false;
}
}
}
How could I check the uniqueness?
This will never give you the isUnique() output that you are looking for. Even if somehow you make it past the ArrayIndexOutOfBound, the code you have written is so inefficient that the JIT will be called every single time you pass a method parameter inside a recursive call.
Try this instead
import java.util.ArrayList;
import java.util.Scanner;
public class Unique {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
//Taking length of the array from the user
System.out.println("Enter the length of the desired array : ");
int length = sc.nextInt();
System.out.println("Please enter the values of the array");
ArrayList<Integer> al = new ArrayList<Integer>();
//Entering the values into the arrayList
for (int i = 0; i < length; i++) {
al.add(sc.nextInt());
}
System.out.println("Enter a number you wish to check : ");
int checkNumber = sc.nextInt();
//Using the built-in method indexOf() to check the occurance of the entered number and return its index if present, else returns -1
System.out.println(al.indexOf(checkNumber)>=0?"The entered number is present in the array":"The entered number is not present in the array");
}}
The goal of this program is to declare three separate arrays and then write a function to display them in a tabular form. Here's my code:
import java.util.Scanner;
public class MultiDArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("How many rows?");
int length = input.nextInt();
int [] ID = new int[length];
for(int counter = 0; counter<length; counter++) {
System.out.println("Enter ID number "+(counter+1));
ID[counter] = input.nextInt();
}
Scanner scan = new Scanner(System.in);
System.out.println("How many names?");
int words = scan.nextInt();
String [] Name = new String[words];
for(int counter = 0; counter<words; counter++) {
System.out.println("Enter Name "+(counter+1));
Name[counter] = scan.next();
}
Scanner figure = new Scanner(System.in);
System.out.println("How many Salaries?");
int sal = figure.nextInt();
int []Salary = new int[sal];
for(int counter = 0; counter<sal; counter++) {
System.out.println("Enter Salary "+(counter+1));
Salary[counter] = figure.nextInt();
}
input.close();
scan.close();
figure.close();
System.out.println("ID"+" "+"Name"+" "+"Salary");
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
}
public static String display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
return null;
}
}
Which prints out my system input in this way:
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
null
However, what I would like to see instead is the same without the "null" part.
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
If I do not specify any return type, I get errors.
You are returning null and then concatenating it in your calling println statement
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
You could do something like
System.out.print("Content of Array: ");
String ret = display(ID, Name, Salary);
If you are trying to write a method without a return type, use void. You shouldn't be concatenating a void return to a string though.
public static void display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
}
Basically I have to prompt a user to enter 10 string values, and then in another loop print them in ascending order, then in a final loop, print them in descending order. My array is bringing back null, obviously because I am not prompting users to enter actual information into the array object. I am really stuck on this. I know I need to somehow reference the "userStrings[]" array in my first while loop. I keep researching and keep getting integer loops questions and For loops. This has to be a while loop. I just can no figure out how to get the userStrings[] to actually fill up when the user enters the values. How do I get it linked in the loop?
public class HomeWork10
{
public static void main(String[] args)
{
String[] userStrings = new String[10];
int count = 0;
int count2 = 0;
while (count < 10)
{
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
count++;
}
while (count2 < 1)
{
System.out.println(Arrays.asList(userStrings));
count2++;
}
}
}
You are not putting the values in the String[]
Do it like this:
while (count < 10) {
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
userStrings[count] = userInput;
count++;
}
Also, declare Scanner input = new Scanner(System.in) outside your while() {...}
See below code snippet may solve your problem.
package com.suresh;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args) {
String[] userStrings = new String[10];
int count = 0;
System.out.println("\t Reading Array Elements ");
while (count < 10) {
System.out.print("\t Please enter a string value : ");
Scanner input = new Scanner(System.in);
userStrings[count] = input.next();
count++;
}
System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
System.out.println("\t ASCENDING ORDER ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
System.out.println("\t DESCENDING ORDER ");
Collections.sort(Arrays.asList(userStrings), new StringDescComparator());
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
}
static class StringAscComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
static class StringDescComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
You created the array with 'String[] userStrings = new String[10];' and inside your while loop to access it you need to do something like this 'userStrings[0] = input.next()' This says the first item in the array userStrings will be set to input.next(). I'm not great at java so I'm not sure what input.next() will do though.
I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.