A very basic java outprint issue - java

I want a specific command to print on the same line but it prints on different lines and I can't figure out a simple fix for it.
package lab10;
import java.util.Scanner;
public class PrintArray {
public static void main(String[] args) {
int numItems;
int[] items;
Scanner scan = new Scanner (System.in);
System.out.println("Enter the number of items");
numItems = scan.nextInt();
items = new int [numItems];
if (items.length > 0);{
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
}
}
for (int i = 0; i < items.length; ++i) {
if (i== 0) {
System.out.println("The values are:" + items[i]);
}else {
System.out.println("The values are:" + items[i] + "," + " ");
}
}
}
}
Expected result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1, 2, 3
Actual result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1
The values are:2,
The values are:3,

Instead of i == 0 you want items.length == 0, and "is" not "are". Also, you'll need additional logic to handle joining the values (and use System.out.print to avoid printing a newline). Like,
if (items.length != 0) {
System.out.print("The values are: ");
}
for (int i = 0; i < items.length; ++i) {
if (items.length == 1) {
System.out.print("The value is: " + items[i]);
} else {
if (i != 0) {
System.out.print(", ");
}
System.out.print(items[i]);
}
}
System.out.println();

I think this approach may be cleaner.
StringJoiner joiner = new StringJoiner(", ", "The values are:", "");
if (items.length > 0){
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
joiner.add(items[i]);
}
}
System.out.println(joiner.toString());
BTW, at this line
if (items.length > 0);{
the semicolon(;) should not be there.

Related

Can this lengthy if-else Java code be improved by using arrays?

I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}

Index match max/min scores (Java)

I am working through a coding assignment and am close to completion save for my final print statement which needs to match names w/ scores for max and min.
I have been able to get appropriate values in two sentences using two if statements, but I am a bit stumped on how to get my indexing correct to align names to scores w/ max and min.
I am not able to use classes or additional / different methods other than arrays and indexing.
//Create method StudentMax
private static int StudentMax(int[] Scores) {
int ScoreMax = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] > ScoreMax){
ScoreMax = Scores[i];
}
}
return ScoreMax;
}
//Create method StudentMin
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
}
}
return ScoreMin;
}
public static void main(String[] args) {
//Call Scanner
Scanner scan = new Scanner(System.in);
//User Welcome
System.out.println("Welcome to the student score sorter.");
System.out.println("\nThis program will accept a number of student names and score values, then find the highest and lowest score.");
System.out.println("\nThen will return the names and max/min scores.");
//User Prompt Enter number of students
System.out.println("\nHow many students would you like to enter: ");
int StudentCount = scan.nextInt();
//Create arrays: Scores, StudentFirst, StudentLast
int [] Scores = new int[StudentCount];
String [] StudentFirst = new String [StudentCount];
String [] StudentLast = new String [StudentCount];
for (int i = 0; i < Scores.length; i++) {
System.out.println("\nStudent " + (i+1)+":");
System.out.println("\nEnter Student's name:");
StudentFirst[i] = scan.next();
StudentLast[i] = scan.next();
System.out.println("\nEnter Student's score (0-100):");
Scores[i] = scan.nextInt();
}
int max = StudentMax(Scores);
int min = StudentMin(Scores);
for (int i = 0; i < Scores.length; i++) {
System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +": " + Scores[i]);
}
for (int i = 0; i < Scores.length; i++) {
if (Scores [i] == max) {
System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
}
}
//This is the sentence format that I need to make work, but I am struggling to understand how to align the index for names and scores.
//System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);
//Scan Close
scan.close();
//Close Program
}
}
Pass back the index not the value
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
int index = 0;
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
index = i;
}
}
return index;
}
Then you can use it later
int index = StudentMax(Scores);
System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);
Note Please pay attention to Java naming conventions

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Search for a number in an array java

I have code that first generates the array with 100 elements, then places randomly generated numbers in each element. I am trying to do a search for a number and if found, print out its index. the code I have so far is:
import java.util.Scanner;
public class Lab01
{
public static void main(String[] args)
{
int[] nums = new int[100];
for (int i = 0; i < nums.length; i++)
{
nums[i] = (int)((Math.random() * 100) + 1);
System.out.print(nums[i] + " , ");
}
System.out.println();
Scanner input = new Scanner(System.in);
int num;
System.out.println("What number would you like to search for?");
num = input.nextInt();
boolean found = false;
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
}
}
}
I put in the print statements to see the values, so I could verify that it was working, but it ALWAYS returns "Not found". What am I missing here?
Try to replace this block, see the explanation in the bottom :
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
With:
int i; // create this
for ( i = 0; i < nums.length; i++) // and remove int from for loop
{
if (num == nums[i])
{
found = true;
break;
}
}
if (found)
{
System.out.println("That number was found at index " + i);
}
else
{
System.out.println("That number was not found.");
}
Explanation:
Put out of for loop the both if condtion and remove the break statement from them and create a int i = 0 before the for loop like above.
You are breaking out of the loop after checking the first number, so if the first number doesn't match, you print "That number was not found". If the first number does match, you break without printing anything. You should only print "That number was not found" after checking all the numbers of the array.
Your if statement should come after the for loop, not inside it.
int i = 0;
for (; i < nums.length; i++) {
if (num == nums[i]) {
found = true;
break;
}
}
if (found) {
System.out.println("That number was found at index" + i);
} else {
System.out.println("That number was not found.");
}
Try this :)
public static void main(String[] args) {
int[] tab = {3, 2, 1, 7, 2, 1};
int userInput, i;
Integer index = null;
boolean found = false;
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
userInput = input.nextInt();
for (i = 0; i<tab.length; i++) {
if (tab[i] == userInput) {
found = true;
index = i;
counter++;
}
}
if (found == true) {
System.out.println("Found number: " + userInput + " at index " + index + " and number is found " + counter + " times in array");
} else {
System.out.println("Not found number: " + userInput);
}
}
public class Contains {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
int toFind = 3;
boolean found = false;
for (int n : num) {
if (n == toFind) {
found = true;
break;
}
}
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found.");
}
}

How can I get this program to print out the numbers the user entered?

Here's my code:
import java.util.*;
public class InputSum
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1)
{
j += i;
i = input.nextInt();
}
System.out.println("Entered Number: " + i);
System.out.println("The Sum: " + j);
}
}
As of now my output is:
Entered Number: -1
The Sum: (Sum of the numbers entered)
Print them inside the loop :
while (i != -1)
{
System.out.println("Entered Number: " + i);
j += i;
i = input.nextInt();
}
System.out.println("The Sum: " + j);
Or it you want to print them in a single line :
List numbers = new ArrayList<Integer>();
while (i != -1)
{
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("\nThe Sum: " + j);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1) {
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: ");
for (int a = 0; a < numbers.size(); a++) {
System.out.print(" " + numbers.get(a));
}
System.out.println("The Sum: " + j);
}
This should work to print the numbers. You can use an arraylist to store the numbers and then if you need them for later calculations they are still stored in the arraylist.
package net.rajkannan.stackoverflow;
import java.util.*;
public class InputSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
String numbers = "";
while (i != -1) {
j += i;
numbers = numbers + i + " ";
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("The Sum: " + j);
}
}

Categories