Print Array Separated By Comma's [duplicate] - java

This question already has answers here:
A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate]
(15 answers)
Closed 6 years ago.
I need to print this array without having he last array item print with a comma. I have tried setting i to be less than 3 but it will not work. :/ I cannot get this last array entry to print all by itself. This is homework so please do not feel the need to give me the answer just a nudge in the right direction would help!
import java.util.Scanner;
public class PrintWithComma {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] hourlyTemp = new int[NUM_VALS];
int i = 0;
hourlyTemp[0] = 90;
hourlyTemp[1] = 92;
hourlyTemp[2] = 94;
hourlyTemp[3] = 95;
for(i = 0; i < NUM_VALS; i++){
if(hourlyTemp[i] < NUM_VALS);
System.out.print(hourlyTemp[i]);
}
System.out.println("");
return;
}
}

Since you just want a nudge in the correct direction,
if(hourlyTemp[i] < NUM_VALS);
Remove the semicolon at the end of that if (it terminates the if body). Also, I suggest you always use braces
if(hourlyTemp[i] < NUM_VALS) {
// ...
}
I also think you wanted i + 1 < NUM_VALS and System.out.print(", "); Of course, you might also use
System.out.println(Arrays.toString(hourlyTemp));
Edit
Based on your comment below you seem to want something like
for (i = 0; i < NUM_VALS; i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(hourlyTemp[i]);
}
System.out.println("");

Related

Counting triangles in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
question i am trying to solve.
You are given n triangles.
You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle.
sample input:
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
here is my code:
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] = arr[i][j]+arr[i][j+1]; //possible error
}
}
for (int i=0;i<testCases;i++){
for (int j=i+1;j<testCases;j++) { //possible error
if (result[i]!=result[j]){
count++;
}
}
}
System.out.println(count);
}
}
error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at P1.TestClass.main(Solution.java:21)
how to correct the loops so as to not get the errors(note there maybe other errors than the one's i have highlighted) also some better ways of solving this problem are appreciated.
Your program has an ArrayIndexOutOfBoundException in the line result[i] = arr[i][j]+arr[i][j+1];. And I am not sure your second set of nested loops achieve what you want (Summing the triangles). Here is something that can work.
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
//This section sums each set of three
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] += arr[i][j];
}
}
//This section counts values that are not duplicated
for (int i=0;i<testCases;i++){
boolean hasDuplicate = false;
for (int j=0;j<testCases;j++) {
if (i == j) continue; //skip comparison of value against itself
if (result[i]==result[j]){
hasDuplicate = true; //duplicate found
}
}
if (!hasDuplicate) count++;
}
System.out.println(count); //display number of unique entries
}
}
I don't want to be doing any homework for you, so I'll give you some pointers. Try not to have a look at a solution I have come up with below before trying it yourself again though.
I'd use an ArrayList to store the test data given to you. They're really useful and Java has great support for them.
result[i] = arr[i][j]+arr[i][j+1]; This breaks because j+1 will always be one over the final index of your array.
You can sort strings alphabetically using Arrays.sort which will make comparing triangles much easier, as possible combinations will all end up the same.
Collections.frequency will tell you how many times an element appears in your ArrayList.
My solution certainly isn't the best, and uses more advanced things as apposed to just arrays and booleans, but it works and produces the right answer at the end. It shows that you can solve problems in many different ways!
public static void main(String[] args) {
ArrayList<String> triangleArray = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
int uniqueTriangles = 0;
// Ask for input, and store in a string that remove all whitespace
System.out.print("Enter triangle sides in format abc separated by a comma:");
String input = scanner.nextLine().trim().replaceAll("\\s", "");
triangleArray.addAll(Arrays.asList(input.split(",")));
// For each item, check it is three characters, and if so, reorder them in
// ascending order i.e 726 => 267
for (int i = 0; i < triangleArray.size(); i++) {
if (triangleArray.get(i).length() != 3) {
triangleArray.remove(i);
}
// Split the triangle string into a character array and sort 'alphabetically'
char[] charArray = triangleArray.get(i).toCharArray();
Arrays.sort(charArray);
triangleArray.set(i, new String(charArray));
}
// Now go through them all again and see if any are unique
for (String s : triangleArray) {
if (Collections.frequency(triangleArray, s) < 2) {
uniqueTriangles++;
}
}
System.out.println(uniqueTriangles);
}

Array Index Out Of Bounds Exception Java Prime Numbers [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I've been trying to dive into java development and have gone for a relatively easy problem of finding prime numbers, however, I keep getting errors and can't see what I've done wrong, any help?
I've been toiling over my computer for an infuriating while and have tried everything, even rewriting the code from beginning
public class HelloWorld{
public static void main(String []args){
int[] check = {2};
//cycle through numbers 1-100
for (int i = 1; i < 100; i++) {
//cycle through numbers to be checked against i
for (int x = 0; x < 101; x++) {
//check if the current itteration of i has no multiples
if (i%check[x] == 0) {
check[i] = i;
} else {
// print any prime numbers
System.out.print(i);
check[i] = i;
}
}
}
}
}
The immediate cause of your error is that you defined the check[] array to have a size of 1, but you are trying to access elements higher than that, which don't exist. However, I don't think that you really need that array here. Consider this version:
for (int i=2; i < 100; i++) {
boolean match = true;
for (int x=2; x <= Math.sqrt(i); x++) {
if (i % x == 0) {
match = false;
break;
}
}
if (match) {
System.out.println("Prime number: " + i);
}
}
Note that the inner loop in x only needs to go as high as the square root of the outer i value. This is because any value greater than sqrt(i) can't possible divide it.
It is because your array has length 1
and you are trying to access out of bound indexes. In case you are lopping 0 to 101 You can initialize your array like this int [] check =new int [101]

Creating a User-Input Asterisk Triangle using Java

I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.

Removing space " " after last element [duplicate]

This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 5 years ago.
Extension to: Largest array / Comparing arrays (fresh view?)
Could someone give me a hint/solution how could I change code, so after the last output number it wouldn't add space after it?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] productsAndCustomers = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] hind = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] raha = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
for (int m : raha) {
int largest = Integer.MIN_VALUE;
for (int p : hind) {
if (p > largest && p <= m) {
largest = p;
}
}
System.out.print(largest + " ");
}
}
}
Although it shows the right answer, It has to be that it won't show that spacing after that last output number. What would be the best option?
You can create a variable space and initialize it with a space after the first iteration like this :
String space = "";
for (int m : raha) {
//Your code...
System.out.print(space + largest);
space = " ";
}
Good idea is to use StringBuilder - you could use method append() to add all largest and after the for loop you could use its delete() method to get rid of last character.
I would suggest just using a regular, not an enhanced for loop so you can know when you are checking the raha array's last element.
Try:
for(int i = 0; i < raha.length; i++) {
// Your code
if(raha[i] != raha.length - 1)
System.out.println(largest + " ");
else
System.out.println(largest);
}
If you're using Java 8, then there's a simple method: instead of printing the results right away, you can collect them into a collection, and then use String.join method:
List<String> results = new ArrayList<>();
for (int m : raha) {
int largest = Integer.MIN_VALUE;
for (int p : hind) {
if (p > largest && p <= m) {
largest = p;
}
}
results.add(Integer.toString(largest));
}
System.out.println(String.join(" ", results));
If you're not using Java 8, then you will have to use some third party library that provides a similar join method.
If you don't want to collect the results, then you will have to track the index (so use a regular for loop instead of outer foreach) and omit the space for the last index.
You can iterate over array with for loop and implement simple if check to see if current iteration is last one:
if (i == array.length - 1)
System.out.print(element);
else
System.out.print(element + " ");
There are many more different ways, this is one of the easiest I can remember.

Making a triangle using characters from the user input in java programing [duplicate]

This question already has answers here:
Java Homework - Printing a triangle pattern?
(9 answers)
Closed 8 years ago.
I am new to coding and using java. I have been working on this java code for quite awhile now and I just cannot figure it out. I am trying to write a program that takes as input a string, and it outputs the string in a sequence of lines, first character, then next two characters, then next three characters and so on. But the last line could be short depending on the size of the original string. An example output would be:
String? abcdefghijklmnopqrstuvwxyz0123456789
a
bc
def
ghij
klmno
pqrstu
vwxyz01
23456789
This is what I have down right now, I have tried a few things
import java.util.Scanner;
public class TrianglingPhrase {
public static void main(String[] args) {
// declare variables
String phrase;
int start = 0;
// get input
Scanner scan = new Scanner(System.in);
System.out.print("String? ");
phrase = scan.nextLine();
while(start < phrase.length()) {
String row = phrase.substring(start, start + 1);
start++;
System.out.println(row);
}
}
}
Also this is the output I get with this code:
String? abc123
a
b
c
1
2
3
whatever you do substring(start, start+1) may only produce strings of length 1. So at least this has to grow continuously. With the var n in this case. It should stop to grow whenever it start+n>length()
int n=0;
while(start < phrase.length()) {
n++;
if(start+n > phrase.length())
n=phrase.length()-start;
String row = phrase.substring(start, start + n);
start+=n;
System.out.println(row);
}
Since these are the so called triangle numbers You can model them with i*(i+1)/2. Start keeps track of the where the old end was so you can do this:
int start = 0;
int end = 1;
for (int i = 2; end <= phrase.length(); i++) {
String row = phrase.substring(start, end);
System.out.println(row);
start = end;
end = (i * (i + 1) / 2);
}
}

Categories