How to quit scanner when input is negative? - java

This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.

You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}

Related

Finding best subarray sum and returning it and the subarray

I am relatively new to Java and to coding as well and am currently trying to solve a subset problem.
The goal is to have the user input the amount of numbers and then input every number up to the amount specified, with the computer asking for every n-th number accordingly.
Afterwards the computer should calculate the sum of all subsets, and return the one closest to pi, as well as the subset in this form [x,y,z] within the same line.
I managed the first part just fine, although it might have been improved with a switch-case for convenience. It adds the input numbers into the array
But I struggle with the second part of this problem, and I have no idea how to progress/arrange the code so that it outputs the desired result. The suggestion I got was that, a for-loop for a set with n elements :
for a from 0 to 2^n
for i from 0 to n
when the binary representation of x on has a 1 at the i-th position
add data[i] to solution.
This should supposedly find all subsets of an array. After that I should add each element, check if the distance from pi decreases and add the element to the solution set. Or at least that is the goal, but my code is not functional as I don't know where to start arranging it. I also don't know what to initialize bestsum with, or how the binary representation algorithm works, or how to add elements to the solution array in order.
Edit : I have made progress, the code below outputs all the subarrays, and it properly calculates the closest sum, but I have no idea how to 'save' the best subarray (subarray with the closest sum) so that I can output it at the end with the sum. I am quite new so I haven't learned about lists or even methods, but this problem in this book at this chapter and I would like to solve it with the suggested method and possibly only simple loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
double[] data = new double[count];
double [] solution = new double[count];
double bestsum = 0.0;
for (int i = 0; i < count; i++) {
if ((i + 1) % 10 == 1) {
System.out.println("Enter " + (i + 1) + "st number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 2) {
System.out.println("Enter " + (i + 1) + "nd number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 3) {
System.out.println("Enter " + (i + 1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i + 1) + "th number: ");
data[i] = input.nextDouble();
}
}
for (int j = 0; j <(1 << count); j++) {
System.out.print("{ ");
double sum = 0.0;
for (int x = 0; x < count; x++) {
if ((j & (1 << x)) > 0) {
System.out.print(data[x] + " ");
sum = sum + data[x];
}
solution[x] = data[x];
}
System.out.println("}");
if (Math.abs(sum - Math.PI) < Math.abs(bestsum - Math.PI)) {
bestsum = sum;
}
}
System.out.println(bestsum);
System.out.println(Arrays.toString(solution));
}
}
Here's my solution to this problem.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
Double data[] = new Double[count];
Double bestsum = 0.0;
List<Double> bestArray= Collections.emptyList();
Set<List<Double>> possibleArrays = new LinkedHashSet<>();
for (int i = 0; i < count; i++) {
if (i == 0) {
System.out.println("Enter " + (i+1) + "st number: ");
data[i] = input.nextDouble();
} else if (i == 1) {
System.out.println("Enter " + (i+1) + "nd number: ");
data[i] = input.nextDouble();
} else if (i == 2) {
System.out.println("Enter " + (i+1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i+1) + "th number: ");
data[i] = input.nextDouble();
}
}
input.close();
for (int i = 0; i < (1<<count); i++)
{
int m = 1; // m is used to check set bit in binary representation.
List<Double> currentArray = new ArrayList<>();
for (int j = 0; j < count; j++)
{
if ((i & m) > 0)
{
currentArray.add(data[j]);
}
m = m << 1;
}
possibleArrays.add(currentArray);
}
Iterator<List<Double>> iterator = possibleArrays.iterator();
iterator.next();
for (int i = 1; i < possibleArrays.size(); i++) {
Double sum=0.0;
List<Double> currentArray = iterator.next();
sum = currentArray.stream().collect(Collectors.summingDouble(Double::doubleValue));
if(Math.abs(sum-Math.PI)<Math.abs(bestsum-Math.PI)) {
bestArray = currentArray;
bestsum = sum;
}
}
System.out.println("possibleArrays: " + possibleArrays);
System.out.println("solution: " + bestArray);
System.out.println("bestsum: " + bestsum);
}

Java Array: Finding how many numbers are less then the Mean

Okay so im trying to find the amount of numbers that are less then
the mean of the first array. Everything but the last part is working and i
cant figure it out. The code at the bottom is what im having problems with.
for example. if i enter 1 2 3 4 5. the mean is 3 and, 1 and 2 are less then 3. so the answer would be 2 numbers.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("How many integers should we analyze?" );
int num;
num=in.nextInt();
while ( num <= 2)
{
System.out.println( "Please reenter, integer must be greater than 1" );
num=in.nextInt();
}
int[] arr = new int[num];
System.out.println( "Please enter the "+ num +" integers:" );
for (int i = 0; i < arr.length; i++)
{
arr[i] = in.nextInt();
}
System.out.print("Number of integers input: " + num);
System.out.println();
double total = 0;
for( int element : arr) {
total += element;
}
System.out.print("Total: " + (int) total);
System.out.println();
double mean = 0;
if ( arr.length > 0) {
mean = total / arr.length;
}
System.out.print("Mean: " + mean );
int big = arr[0];
for (int i = 0 ; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
}
}
System.out.println();
System.out.print("Largest: " + big);
System.out.println();
///////////////////////////////////////////////////////////////////////////////////////////////
int less;
for(int i=0;i<mean;i++) {
int num2 = i;
int[] arr2 = new int[num2];
int count = 0;
while ( num2 != 0 )
{
num2/=10;
++count;
System.out.print("Numbers less than the mean: " + count);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
}
}
you could use this code below
int count = 0;
for(int i =0;i< arr.length;i++) {
if(arr[i] < mean)
count++;
}
System.out.println("numbers less than mean " + count);
what this does is it loops through all of the original integers and if one is less than the mean, the count variable goes up by 1.
You should iterate over the array and check each element if they are under the mean. If yes, then increment an integer.
int less = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < mean) {
less++;
}
}
System.out.print("Numbers less than the mean: " + less);

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

3 Dimensional Tic Tac Toe prints only one dimension

I'm starting on a program to make a 3D tic tac toe game, and am running into a few problems. The game is supposed to be 4x4x4. I'm not sure why the multiple dimensions are not being printed, and I'm also not sure why my entered value isn't appearing on the one level that shows. Code below. Any help would be awesome. Thanks!
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int draw = 64;
int n = 0;
int board[][][] = new int[4][4][4];
while (n < draw) {
System.out.println("Type your move as one three digit number(lrc)");
int input = scan.nextInt();
int level = input / 100;
int row = input % 100 / 10;
int column = input % 10;
System.out.println(level);
System.out.println(row);
System.out.println(column);
board[level][row][column] = 1;
for (int i = 3; i >= 0; i--) { //level
for (int h = 3; h >= 0; h--) { //row
for (int temp = h; temp >= 0; temp--) {
System.out.print(" ");
}
System.out.print(i + "" + h + " ");
for (int j = 0; j <= 3; j++) { //column
if (board[i][h][j] == 0) {
System.out.print("_ ");
}
if (board[i][h][j] == 1) {
System.out.print("X ");
n++;
}
if (board[i][h][j] == 5) {
System.out.print("O ");
n++;
}
}
System.out.println();
}
System.out.println();
}
System.out.println("\n 0 1 2 3");
}
}
}
In this line
for (int temp = h; h > 0; h--) {
you are decrementing h rather than temp so in the loops below the value of h will always be 1
After this change
change for (int temp = h; temp >= 0; temp--) {
System.out.println(" ");
}
to simply System.out.println(" ");

Brute Force Algorithm Issue

I've look over the code several time but I keep getting a Array Out of Bound at the line that states:
sum = sum + vectorArray[z]; }
Can anyone see what's wrong?
public class HW1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The numbers for n are not relevant
System.out.println("Please enter a number for the length of n.");
int n = input.nextInt();
// Creates an array with n values
int[] vectorArray = new int[n];
// Inputs random numbers into the array ranging from -100 to 100.
int dummy;
int temp = 0;
// Loop to generate negative and positive numbers into the array
for (int i = 0; i < n; i++) {
dummy = (int)(Math.random()*2);
if (dummy == 0) {
temp = -1;
} else {
temp = 1; }
vectorArray[i] = ((int)(Math.random()*101)) * temp;
System.out.println(vectorArray[i]); }
int max = -1;
int sum;
for (int x = 0; x < vectorArray.length; x++) {
for (int y = x; x < vectorArray.length; y++) {
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }
max = Math.max(max, sum);
} }
System.out.println("The max: " + max);
}
}
change x to y in the for loop
for (int y = x; y < vectorArray.length; y++) {
^
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }

Categories

Resources